Adding MainTestTraversal method.
This commit is contained in:
@@ -65,9 +65,37 @@ public class MainExercises
|
||||
- Number of columns: matrix[0].length (if rectangular)
|
||||
*/
|
||||
public int[] spiralTraversal(int[][] matrix) {
|
||||
// todo
|
||||
return null;
|
||||
int rows = matrix.length;
|
||||
int cols = matrix[0].length;
|
||||
int[] result = new int[rows * cols];
|
||||
int index = 0;
|
||||
int top = 0, bottom = rows - 1;
|
||||
int left = 0, right = cols - 1;
|
||||
while (top <= bottom && left <= right) {
|
||||
for (int j = left; j <= right; j++) {
|
||||
result[index++] = matrix[top][j];
|
||||
}
|
||||
top++;
|
||||
for (int i = top; i <= bottom; i++) {
|
||||
result[index++] = matrix[i][right];
|
||||
}
|
||||
right--;
|
||||
if (top <= bottom) {
|
||||
for (int j = right; j >= left; j--) {
|
||||
result[index++] = matrix[bottom][j];
|
||||
}
|
||||
bottom--;
|
||||
}
|
||||
if (left <= right) {
|
||||
for (int i = bottom; i >= top; i--) {
|
||||
result[index++] = matrix[i][left];
|
||||
}
|
||||
left++;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
integer partitioning is a combinatorics problem in discreet maths
|
||||
|
||||
Reference in New Issue
Block a user