Implement Traversal method

This commit is contained in:
2026-04-21 17:12:50 +03:30
parent 0a60c2e5e9
commit c59b80f87c
+42 -2
View File
@@ -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;
} }
/* /*