File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number } n
3+ * @return {number[][] }
4+ */
5+ let generateMatrix = function ( n ) {
6+ // 记录一个 visited 数组
7+ // 按照 右 -> 下 -> 左 -> 上 的方向不断前进
8+ // 直到遇到边界或者已经访问过的元素 则切换成下一个方向
9+ let dirs = [
10+ [ 0 , 1 ] , // 右
11+ [ 1 , 0 ] , // 下
12+ [ 0 , - 1 ] , // 左
13+ [ - 1 , 0 ] , // 上
14+ ]
15+
16+ let currentDirIndex = 0
17+
18+ let visited = [ ]
19+ for ( let y = 0 ; y < n ; y ++ ) {
20+ visited [ y ] = [ ]
21+ }
22+ let isValid = ( y , x ) => {
23+ return y >= 0 && y < n && x >= 0 && x < n && ! visited [ y ] [ x ]
24+ }
25+
26+ let targetLength = n * n
27+ let res = [ ]
28+ for ( let y = 0 ; y < n ; y ++ ) {
29+ res [ y ] = [ ]
30+ }
31+
32+ let helper = ( y , x , num ) => {
33+ res [ y ] [ x ] = num
34+
35+ if ( num === targetLength ) {
36+ return res
37+ }
38+
39+ visited [ y ] [ x ] = true
40+ let [ diffY , diffX ] = dirs [ currentDirIndex % 4 ]
41+ let nextY = y + diffY
42+ let nextX = x + diffX
43+ if ( ! isValid ( nextY , nextX ) ) {
44+ ; [ diffY , diffX ] = dirs [ ++ currentDirIndex % 4 ]
45+ nextY = y + diffY
46+ nextX = x + diffX
47+ }
48+ helper ( nextY , nextX , num + 1 )
49+ }
50+
51+ helper ( 0 , 0 , 1 )
52+
53+ return res
54+ }
You can’t perform that action at this time.
0 commit comments