Assignment finished - Completed Main and Bonus exercises #1

Merged
peyman merged 10 commits from develop into main 2026-04-25 21:48:14 +00:00
Showing only changes of commit c59b80f87c - Show all commits
+42 -2
View File
@@ -72,8 +72,48 @@ 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 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;
}
/*