分析
-
本题的考点:偏移量技巧。
-
如果当前位置是
(x, y)
,则该点的上右下左的坐标分别为:(x-1, y), (x, y+1), (x+1, y), (x, y-1)
。偏移量为(-1, 0), (0, 1), (1, 0), (0, -1)
。
代码
- C++
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
for (int i = 1, x = 0, y = 0, d = 0; i <= n * n; i++) {
res[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= n || res[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return res;
}
};
- Java
public class Solution {
public int[][] generateMatrix(int n) {
int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
int[][] res = new int[n][n];
int x = 0, y = 0, d = 1;
for (int i = 1; i <= n * n; i++) {
res[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= n || res[a][b] != 0) {
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
return res;
}
}
时空复杂度分析
-
时间复杂度:$O(n^2)$。
-
空间复杂度:考虑存储结果的数组 $O(n^2)$。