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 {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> ints = new ArrayList<Integer>();
if(matrix==null || matrix.length==0) {
return ints;
}
int m = matrix.length;
int n = matrix[0].length;
int loop = 0;
while(ints.size()<m*n) {
for(int i=loop;i<n-loop;i++) {
ints.add(matrix[loop][i]);
}
if(ints.size()==m*n) {
break;
}
for(int i=loop+1;i<m-loop-1;i++) {
ints.add(matrix[i][n-loop-1]);
}
if(ints.size()==m*n) {
break;
}
for(int i=n-loop-1;i>=loop;i--) {
ints.add(matrix[m-loop-1][i]);
}
if(ints.size()==m*n) {
break;
}
for(int i=m-loop-2;i>loop;i--) {
ints.add(matrix[i][loop]);
}
loop++;
}
return ints;
}
}
没有评论:
发表评论