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

Example 1:

[LeetCode] 59. Spiral Matrix II_array

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,请输出一个n x n的矩阵,被从1到n方这n方个数字填满。填满的方式同54题。

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

时间O(n)

空间O(n^2)

JavaScript实现

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

 

Java实现

 1 class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int[][] matrix = new int[n][n];
 4         int rowBegin = 0;
 5         int rowEnd = n - 1;
 6         int colBegin = 0;
 7         int colEnd = n - 1;
 8         int num = 1;
 9 
10         while (rowBegin <= rowEnd && colBegin <= colEnd) {
11             for (int i = colBegin; i <= colEnd; i++) {
12                 matrix[rowBegin][i] = num++;
13             }
14             rowBegin++;
15 
16             for (int i = rowBegin; i <= rowEnd; i++) {
17                 matrix[i][colEnd] = num++;
18             }
19             colEnd--;
20 
21             for (int i = colEnd; i >= colBegin; i--) {
22                 matrix[rowEnd][i] = num++;
23             }
24             rowEnd--;
25 
26             for (int i = rowEnd; i >= rowBegin; i--) {
27                 matrix[i][colBegin] = num++;
28             }
29             colBegin++;
30         }
31         return matrix;
32     }
33 }

 

LeetCode 题目总结