54. 螺旋矩阵
题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order=new ArrayList<Integer>();
if(matrix==null)
return order;
int rows=matrix.length,cols=matrix[0].length;
boolean[][] visted=new boolean[rows][cols];
int total=rows*cols;
int row=0,col=0;
int[][] directions={{0,1},{1,0},{0,-1},{-1,0}};
int directionsIndex=0;
for(int i=0;i<total;i++){
order.add(matrix[row][col]);
visted[row][col]=true;
int nextrow=row+directions[directionsIndex][0],nextcol=col+directions[directionsIndex][1];
if(nextrow<0||nextrow>=rows||nextcol<0||nextcol>=cols||visted[nextrow][nextcol]==true)
directionsIndex=(directionsIndex+1)%4;
row+=directions[directionsIndex][0];
col+=directions[directionsIndex][1];
}
return order;
}
}
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<Integer>();
if(matrix.length==0)
return res;
int up=0,down=matrix.length-1,left=0,right=matrix[0].length-1;
while(true){
for(int col=left;col<=right;col++)
res.add(matrix[up][col]);
if(++up>down) break;
for(int row=up;row<=down;row++)
res.add(matrix[row][right]);
if(--right<left) break;
for(int col=right;col>=left;col--)
res.add(matrix[down][col]);
if(--down<up) break;
for(int row=down;row>=up;row--)
res.add(matrix[row][left]);
if(++left>right) break;
}
return res;
}
}
思考
我做过类似的题目,但是我碰到还是不会,(⊙o⊙)…
评论区大佬真多。