题解 | #螺旋矩阵#
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
java代码最简洁最通俗易懂
按照右(x不变, y++, 后同理), 下, 左, 上的顺序遍历
注意第一个点要特殊处理
import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
if( matrix.length == 0 ) return res;
int m = matrix.length;
int n = matrix[0].length;
boolean[][] vis = new boolean[m][n];
int x = 0, y = 0;
res.add(matrix[x][y]);
vis[x][y] = true;
while(res.size() < m*n){
while( y + 1 < n && !vis[x][y+1] ){ res.add(matrix[x][y+1]); vis[x][++y] = true; }
while( x + 1 < m && !vis[x + 1][y] ){ res.add(matrix[x+1][y]); vis[++x][y] = true; }
while( y - 1 >= 0 && !vis[x][ y-1 ] ){ res.add(matrix[x][y-1]); vis[x][--y] = true; }
while( x - 1 >= 0 && !vis[x - 1][ y ] ){ res.add(matrix[x - 1][y]); vis[--x][y] = true; }
}
return res;
}
}