Implement Traversal method
This commit is contained in:
@@ -72,8 +72,48 @@ public class MainExercises
|
|||||||
- Number of columns: matrix[0].length (if rectangular)
|
- Number of columns: matrix[0].length (if rectangular)
|
||||||
*/
|
*/
|
||||||
public int[] spiralTraversal(int[][] matrix) {
|
public int[] spiralTraversal(int[][] matrix) {
|
||||||
// todo
|
|
||||||
return null;
|
int rows = matrix.length;
|
||||||
|
int cols = matrix[0].length;
|
||||||
|
|
||||||
|
int[] result = new int[rows * cols];
|
||||||
|
|
||||||
|
int top = 0, bottom = rows - 1, left = 0, right = cols - 1;
|
||||||
|
int id = 0;
|
||||||
|
|
||||||
|
while(top <= bottom && left <= right){ // reaching the center
|
||||||
|
|
||||||
|
for(int col = left; col <= right; col++){
|
||||||
|
result[id] = matrix[top][col];
|
||||||
|
id++;
|
||||||
|
}
|
||||||
|
top++;
|
||||||
|
|
||||||
|
for(int row = top; row <= bottom; row++){
|
||||||
|
result[id] = matrix[row][right];
|
||||||
|
id++;
|
||||||
|
}
|
||||||
|
right--;
|
||||||
|
|
||||||
|
if(top <= right){
|
||||||
|
for(int col = right; col >= left; col--){
|
||||||
|
result[id] = matrix[bottom][col];
|
||||||
|
id++;
|
||||||
|
}
|
||||||
|
bottom--;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(left <= right){
|
||||||
|
for(int row = bottom; row >= top; row--){
|
||||||
|
result[id] = matrix[row][left];
|
||||||
|
id++;
|
||||||
|
}
|
||||||
|
left++;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
Reference in New Issue
Block a user