Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
public class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> spiralOrder(int[][] matrix) {
help(matrix);
return list;
}
private void help (int [][]matrix){
if(matrix.length==0) return;
int row = matrix.length;
int column = matrix[0].length;
if(row == 1){
for(int i=0;i<column;i++) list.add(matrix[0][i]);
}else if(column == 1){
for(int i=0;i<row;i++) list.add(matrix[i][0]);
}else{
for (int i = 0; i < column - 1; i++) list.add(matrix[0][i]);
for (int i = 0; i < row - 1; i++) list.add(matrix[i][column - 1]);
for (int i = column - 1; i > 0; i--)list.add(matrix[row - 1][i]);
for (int i = row - 1; i > 0; i--)list.add(matrix[i][0]);
}
if(row-2<=0||column-2<=0) return;
int [][]matrix2 = new int[row-2][column-2];
for(int i =0,j=1;i<row-2;i++,j++) matrix2[i] = Arrays.copyOfRange(matrix[j],1, column-1);
help(matrix2);
}
}