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]
.
题意:蛇形遍历二维数组
分类:数组
解法1:思路要顺畅,我们观察一个次遍历,可以发现,每次都是从(i,i)这个坐标开始,例如起始坐标是(0,0),一圈下来,坐标是(1,1)
于是循环结束条件是i*2<cols
对于每圈,首先计算出结束的x,y坐标,用于边界判断
最后从左到右,从上到下,从右到左,从下到上,完成一圈
其中要注意,不是每次都能向下走,这里我使用了一个二维数组来简单判断某个元素是否被访问过
从而判断是否能继续走,当然还有更加高效的办法,只是这个方法比较简单,不用考虑很多情况
- public class Solution {
- public List<Integer> spiralOrder(int[][] matrix) {
- ArrayList<Integer> arr = new ArrayList<Integer>();
- int rows = matrix.length;
- if(rows==0) return arr;
- int cols = matrix[0].length;
- boolean vis[][] = new boolean[rows][cols];
- int x = 0;
- while(x*2<cols && x*2<rows){
- int endX = rows-x-1;
- int endY = cols-x-1;
- for(int i=x;i<=endY;i++){
- if(!vis[x][i]){
- arr.add(matrix[x][i]);
- vis[x][i] = true;
- }
- }
- for(int i=x+1;i<=endX;i++){
- if(!vis[i][endY]){
- arr.add(matrix[i][endY]);
- vis[i][endY] = true;
- }
- }
- for(int i=endY-1;i>=x;i--){
- if(!vis[endX][i]){
- arr.add(matrix[endX][i]);
- vis[endX][i] = true;
- }
- }
- for(int i=endX-1;i>x;i--){
- if(!vis[i][x]){
- arr.add(matrix[i][x]);
- vis[i][x] = true;
- }
- }
- x = x + 1;
- }
- return arr;
- }
- }
解法2:优化每次过程,使用标志来记录每次的边界,包括left,top,right,bittom
- public class Solution {
- public List<Integer> spiralOrder(int[][] matrix) {
- ArrayList<Integer> res = new ArrayList<Integer>();
- int n = matrix.length;
- if(n==0) return res;
- int m = matrix[0].length;
- int x = 0,y = 0;
- int count = 0,limit = m*n;
- int right = m-1,bottom = n-1,left = 0,top = 0;
- while(count<limit){
- while(count<limit&&y<=right){res.add(matrix[x][y++]);count++;}
- y--;x++;top++;
- while (count<limit&&x<=bottom) {res.add(matrix[x++][y]);count++;}
- x--;y--;right--;
- while(count<limit&&y>=left) {res.add(matrix[x][y--]);count++;}
- x--;y++;bottom--;
- while(count<limit&&x>=top) {res.add(matrix[x--][y]);count++;}
- x++;y++;left++;
- }
- return res;
- }
- }