LC 59. 螺旋矩阵 II

题目描述

这是 LeetCode 上的 59. 螺旋矩阵 II ,难度为 中等

给你一个正整数 $n$ ,生成一个包含 $1$ 到 $n^2$ 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

示例 1:

1
2
3
输入:n = 3

输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:
1
2
3
输入:n = 1

输出:[[1]]

提示:

  • $1 <= n <= 20$

按照「形状」进行模拟

我们可以按「圈」进行构建。

使用「左上角」$(x1,y1)$ &「右下角」$(x2,y2)$ 来确定某个「圈」,进行构建。

完成后,令「左上角」&「右下角」往里收,分别得到 $(x1 + 1, y1 + 1)$ 和 $(x2 - 1, y2 - 1)$,执行相同的构建规则。

image.png

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
circle(0, 0, n - 1, n - 1, 1, ans);
return ans;
}
void circle(int x1, int y1, int x2, int y2, int start, int[][] ans) {
if (x2 < x1 || y2 < y1) return ;
if (x1 == x2) {
ans[x1][y1] = start;
return;
}
int val = start;
for (int i = y1; i < y2; i++) ans[x1][i] = val++;
for (int i = x1; i < x2; i++) ans[i][y2] = val++;
for (int i = y2; i > y1; i--) ans[x2][i] = val++;
for (int i = x2; i > x1; i--) ans[i][y1] = val++;
circle(x1 + 1, y1 + 1, x2 - 1, y2 - 1, val, ans);
}
}

  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n^2)$

按照「方向」进行模拟

事实上,我们还可以根据「方向」进行模拟。

因为每一圈的构建都是按照特定的「四个方向」进行的。

这种解法更为简洁。而触发方向转换的时机:

  1. 下一步发生位置溢出
  2. 回到了本圈的起点

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
// 定义四个方向
int[][] dirs = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
for (int x = 0, y = 0, d = 0, i = 1; i <= n * n; i++) {
ans[x][y] = i;
// 下一步要到达的位置
int nx = x + dirs[d][0], ny = y + dirs[d][1];
// 如果下一步发生「溢出」或者已经访问过(说明四个方向已经走过一次)
if (nx < 0 || nx >= n || ny < 0 || ny >= n || ans[nx][ny] != 0) {
d = (d + 1) % 4;
nx = x + dirs[d][0]; ny = y + dirs[d][1];
}
x = nx; y = ny;
}
return ans;
}
}

-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
const int dir[4][2] = { {0,1},{1,0},{0,-1},{-1,0}};
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n,0));
for(int i = 1, x = 0, y = 0, d = 0; i <= n * n; i++){
res[x][y] = i;
int t_x = x + dir[d][0],t_y = y + dir[d][1];
if(t_x < 0 or t_x >= n or t_y < 0 or t_y >= n or res[t_x][t_y] != 0){
d = (d + 1) % 4;
t_x = x + dir[d][0],t_y = y + dir[d][1];
}
x = t_x, y = t_y;
}
return res;
}
};
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n^2)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.59 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!