[LeetCode] 59. Spiral Matrix II

Two helical matrix. It is intended to give the title a number n, output of a request nxn matrix, n is filled from a side to side of the n digits. 54 ways to fill the same title. example,

Example:

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

The problem with the 54 questions the practice is almost the same. To fill is accomplished by finding the boundary row and column movements. First, create a two-dimensional array of nxn with JS and fill with zeros. Traversal time, also in accordance with the right - under - on the order of - left.

Time O (n)

Space O (n ^ 2)

 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 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12306149.html