模拟
还是用老技巧,用一个dx来描述某个方向的i,j坐标变换情况。
int[][] dx = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
如果按题目中的例子来看的话,分别表示向左,下,右,上走时,i,j坐标应该如何变换
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
List<Integer> ans = new ArrayList<>();
if (m <= 0) {
return ans;
}
int n = matrix[0].length;
int[][] dx = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
boolean[][] f = new boolean[m][n];
int cur = 0;
int i = 0, j = 0;
while (true) {
ans.add(matrix[i][j]);
f[i][j] = true;
if (i + dx[cur][0] >= m || i + dx[cur][0] < 0
|| j + dx[cur][1] >= n || j + dx[cur][1] < 0
|| f[i + dx[cur][0]][j + dx[cur][1]]) {
cur = (cur + 1) % 4;
if (i + dx[cur][0] >= m || i + dx[cur][0] < 0
|| j + dx[cur][1] >= n || j + dx[cur][1] < 0
|| f[i + dx[cur][0]][j + dx[cur][1]]) {
break;
}
}
i += dx[cur][0];
j += dx[cur][1];
}
return ans;
}
}
原文地址:https://www.cnblogs.com/acbingo/p/9357251.html
时间: 2024-11-24 07:19:30