所以用Step表示每一次转向,走的实际步数是step / 2
把list变成array
return res.toArray(new int[R * C][2]);
45.43 %
class Solution {
public int[][] spiralMatrixIII(int R, int C, int r0, int c0) {
List<int[]> result = new ArrayList<>();
int[] curr = new int[]{r0, c0};
result.add(new int[]{r0, c0});
int step = 0;
while (result.size() < R * C) {
for (int i = 0; i <= step / 2; i++) {
curr[0] = curr[0] + dirs[step % 4][0];
curr[1] = curr[1] + dirs[step % 4][1];
if (isValid(curr, R, C)) {
result.add(new int[]{curr[0], curr[1]});
}
}
step++;
}
int[][] array = new int[result.size()][];
return result.toArray(array);
}
private int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
private boolean isValid(int[] pos, int R, int C) {
return pos[0] >= 0 && pos[0] < R && pos[1] >= 0 && pos[1] < C;
}
}
No comments:
Post a Comment