Leetcode Hot100 矩阵
54 螺旋矩阵
class Solution {
public int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
public List<Integer> res = new ArrayList<>();
public boolean check(int x,int y,int h,int l){
if(x >= 0 && x < h && y>=0 && y<l)
return true;
return false;
}
public void dfs(int x,int y,int nd,int cnt,int[][] m,boolean[][] visit){
visit[x][y] = true;
res.add(m[x][y]);
if(cnt == m.length * m[0].length)
return ;
for(int i=0;i<4;++i){
nd = (nd + i)%4;
int newx = x + dir[nd][0];
int newy = y + dir[nd][1];
if(check(newx,newy,m.length,m[0].length) && !visit[newx][newy]){
dfs(newx,newy,nd,cnt+1,m,visit);
break;
}
}
}
public List<Integer> spiralOrder(int[][] matrix) {
boolean[][] visit = new boolean[matrix.length][matrix[0].length];
dfs(0,0,0,1,matrix,visit);
return res;
}
}
Tips
Java数组的初始化形式:
- new int[ i ][ j ]:j可以省略
- 静态初始化: { { … } , { … } , … }