Adding MainTestTraversal method.

This commit is contained in:
2026-04-19 15:12:05 +03:30
parent f15ca18ad2
commit 9c2990038d
+30 -2
View File
@@ -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