seconed question

This commit is contained in:
2026-04-23 05:26:28 -07:00
parent ce5e38afc9
commit 8fd66d9681
+48 -2
View File
@@ -1,3 +1,5 @@
import java.util.ArrayList;
public class MainExercises public class MainExercises
{ {
/* /*
@@ -71,10 +73,54 @@ public class MainExercises
- Number of columns: matrix[0].length (if rectangular) - Number of columns: matrix[0].length (if rectangular)
*/ */
public int[] spiralTraversal(int[][] matrix) {
return null; public int[] spiralTraversal(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
int[] result = new int[rows*columns];
int top = 0;
int down = rows-1;
int left = 0;
int right = columns-1;
int counter = 0;
while(top <= down && left <= right){
for (int i = left ; i <= right ; i++){
result[counter] = matrix[top][i];
counter++;
} }
top++;
for(int i = top ; i <= down ; i++){
result[counter] = matrix[i][right];
counter++;
}
right--;
if (counter < rows*columns){
for(int i = right ; i >= left ; i--){
result[counter] = matrix[down][i];
counter++;
}
down--;
for(int i = down ; i >= top ; i--){
result[counter]= matrix[i][left];
counter++;
}
left++;
}
}
return result;
}
/* /*
integer partitioning is a combinatorics problem in discreet maths integer partitioning is a combinatorics problem in discreet maths