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]
.
Subscribe to see which companies asked this question
比较简单,旋转着往里面填数就行,不过这里的方法略繁琐
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int forward = 0;
int i =0,j=0;
List<Integer> ret =new ArrayList<>();
int targetI = 0, targetJ = 0;
if(matrix.length==0)return ret;
int m = matrix.length, n = matrix[0].length;
if(m*n==0)return ret;
if(m*n==1){
ret.add(matrix[0][0]);
return ret;
}
if(m<=n){
targetI=m/2;
if(m%2==1){
targetJ=n-1-targetI;
}else{
targetJ=m-1-targetI;
}
}else{
targetJ=(n-1)/2;
if(n%2==1){
targetI=m-n+targetJ;
}else{
targetI=targetJ+1;
}
}
// outer:
while(true){
switch(forward){
case 0:
if(j==n-1-i){
ret.add(matrix[i][j]);
forward++;
i++;
}else{
ret.add(matrix[i][j]);
j++;
}break;
case 1:
if(i==m-n+j){
ret.add(matrix[i][j]);
forward++;
j--;
}else{
ret.add(matrix[i][j]);
i++;
}break;
case 2:
if(j==m-1-i){
ret.add(matrix[i][j]);
forward++;
i--;
}else{
ret.add(matrix[i][j]);
j--;
}break;
case 3:
if(i==j+1){
ret.add(matrix[i][j]);
forward++;
j++;
}else{
ret.add(matrix[i][j]);
i--;
}break;
}
forward%=4;
if(i==targetI&&j==targetJ)break;
}
ret.add(matrix[i][j]);
return ret;
}
}