本题关键在于模拟数组螺旋的步骤,使用 flag 二维数组标识矩阵某位置是否被访问过,使用 turn 变量指示当前寻找的方向, turn 为0时,代表向右查找, turn 为1时,代表向下查找, turn 为2时,代表向左查找, turn 为3时,代表向上查找,具体的代码如下:
class Solution { public List<Integer> spiralOrder(int[][] matrix) { int turn = 0; int n = matrix.length; int m = matrix[0].length; int i = 0; int j = 0; int[][] flag = new int[n][m]; List<Integer> ans = new ArrayList<>(); while(ans.size() != m*n){ if(turn == 0){ ans.add(matrix[i][j]); flag[i][j]=1; j++; if(j>m-1 || flag[i][j]==1){ turn = (turn+1)%4; j--; i++; continue; } } if(turn == 1){ ans.add(matrix[i][j]); flag[i][j]=1; i++; if(i>n-1 || flag[i][j]==1){ turn = (turn+1)%4; i--; j--; continue; } } if(turn == 2){ ans.add(matrix[i][j]); flag[i][j]=1; j--; if(j<0 || flag[i][j]==1){ turn = (turn+1)%4; j++; i--; continue; } } if(turn == 3){ ans.add(matrix[i][j]); flag[i][j]=1; i--; if(i<0 || flag[i][j]==1){ turn = (turn+1)%4; i++; j++; continue; } } } return ans; } }
标签:LeetCode54,matrix,螺旋,int,turn,flag,数组,ans,-- From: https://www.cnblogs.com/rockdow/p/17729508.html