implement MainExercises.java #1
@@ -1,3 +1,5 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class MainExercises
|
||||
{
|
||||
/*
|
||||
@@ -69,8 +71,50 @@ public class MainExercises
|
||||
- Number of columns: matrix[0].length (if rectangular)
|
||||
*/
|
||||
public int[] spiralTraversal(int[][] matrix) {
|
||||
// todo
|
||||
return null;
|
||||
|
||||
int rows = matrix.length;
|
||||
int columns = matrix[0].length;
|
||||
|
||||
int[] result = new int[rows*columns];
|
||||
int count = 0;
|
||||
|
||||
int top = 0;
|
||||
int bottom = rows - 1;
|
||||
int right = columns - 1;
|
||||
int left = 0;
|
||||
|
||||
while (top <= bottom && left <= right) {
|
||||
|
||||
for(int j = left ; j<=right ; j++) {
|
||||
result[count] = matrix[top][j];
|
||||
count++;
|
||||
}
|
||||
top++;
|
||||
|
||||
for(int i = top ; i<=bottom ; i++) {
|
||||
result[count] = matrix[i][right];
|
||||
count++;
|
||||
}
|
||||
right--;
|
||||
|
||||
if(top <= bottom) {
|
||||
for (int j = right; j >= left; j--) {
|
||||
result[count] = matrix[bottom][j];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
bottom--;
|
||||
|
||||
if(left <= right){
|
||||
for (int i = bottom; i >= top; i--) {
|
||||
result[count] = matrix[i][left];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
left++;
|
||||
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
Reference in New Issue
Block a user