54.Spiral Matrix
题目链接:https://leetcode.com/problems/spiral-matrix/description/
题目大意:给一个数组,蛇形存入list后返回。
法一:模板模拟,注意的是这里给的数组,不一定是n*n的,所以要根据行和列分别计算。代码如下(耗时3ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public List<Integer> spiralOrder(int[][] matrix) { 2 List<Integer> res = new ArrayList<Integer>(); 3 if(matrix.length == 0) { 4 return res; 5 } 6 int num = 1, m = matrix.length, n = matrix[0].length, i = 0, j = 0; 7 res.add(matrix[i][j]); 8 boolean vis[][] = new boolean[matrix.length][matrix[0].length]; 9 vis[i][j] = true; 10 while(num < m * n) { 11 //从左到右 12 while(j < n - 1 && vis[i][j + 1] == false) { 13 res.add(matrix[i][++j]); 14 vis[i][j] = true; 15 num++; 16 } 17 //从上到下 18 while(i < m - 1 && vis[i + 1][j] == false) { 19 res.add(matrix[++i][j]); 20 vis[i][j] = true; 21 num++; 22 } 23 //从右到左 24 while(j > 0 && vis[i][j - 1] == false) { 25 res.add(matrix[i][--j]); 26 vis[i][j] = true; 27 num++; 28 } 29 //从下到上 30 while(i > 0 && vis[i - 1][j] == false) { 31 res.add(matrix[--i][j]); 32 vis[i][j] = true; 33 num++; 34 } 35 } 36 return res; 37 }