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