[LeetCode] 59. Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:
Example 1
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:
Input: n = 1
Output: [[1]]

Constraints:
1 <= n <= 20

螺旋矩阵II。

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

思路

题意是给一个数字 n,请输出一个 n x n 的矩阵,被从 1 到 n 方这 n 方个数字填满。填满的方式同 54 题。

这个题跟 54 题做法几乎一样。也是要通过找到 row 和 column 的边界来完成填充的动作。首先创建一个 n x n 的二维数组并用0填满。遍历的时候,也是按照右 - 下 - 左 - 上的顺序。

复杂度

时间O(n^2)
空间O(n^2)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
// left to right
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
top++;

// top to bottom
for (int i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;

// right to left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
bottom--;
}

// bottom to top
if (left <= right) {
for (int i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
}
}
return matrix;
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
let res = Array(n).fill(0).map(() => Array(n).fill(0));
let rowBegin = 0;
let rowEnd = n - 1;
let colBegin = 0;
let colEnd = n - 1;
let num = 1;

while (rowBegin <= rowEnd && colBegin <= colEnd) {
// right
for (let i = colBegin; i <= colEnd; i++) {
res[rowBegin][i] = num++;
}
rowBegin++;

// down
for (let i = rowBegin; i <= rowEnd; i++) {
res[i][colEnd] = num++;
}
colEnd--;

// left
for (let i = colEnd; i >= colBegin; i--) {
res[rowEnd][i] = num++;
}
rowEnd--;

// up
for (let i = rowEnd; i >= rowBegin; i--) {
res[i][colBegin] = num++;
}
colBegin++;
}
return res;
};

[LeetCode] 59. Spiral Matrix II
https://shurui91.github.io/posts/2293412747.html
Author
Aaron Liu
Posted on
February 14, 2020
Licensed under