spiral matrix
程序员文章站
2022-07-12 09:22:36
...
给定一个n*m的数组然后螺旋打印:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//控制方向的数组。
int[] direction_i = {0,1,0,-1};
int[] direction_j = {1,0,-1,0};
//dir是当前是什么方向,l变向了几次,layer第几层。
int dir = 0,i = 0,j = 0,layer = 0,l = 0,count =0;
List<Integer> res = new ArrayList<>();
if(matrix.length == 0){
return res;
}
int r = matrix.length;
int c= matrix[0].length;
while(count<r*c){
res.add(matrix[i][j]);
layer = (l + 1)/4;
if(dir == 0 && j == c - layer-1 || dir == 1 && i == r - layer - 1|| dir == 2 && j == layer || dir == 3 && i == layer ){
l++;
}
dir = l%4;
i += direction_i[dir];
j += direction_j[dir];
count++;
}
return res;
}
}
转载于:https://www.jianshu.com/p/b3ee0d0f8fe4
上一篇: ssh开发标准(自己陆续总结)
下一篇: Spiral Matrix