File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[][] } grid
3+ * @return {number }
4+ */
5+ let getMaximumGold = function ( grid ) {
6+ let maxY = grid . length
7+ if ( maxY === 0 ) {
8+ return 0
9+ }
10+ let maxX = grid [ 0 ] . length
11+
12+ let visited = [ ]
13+ for ( let y = 0 ; y < maxY ; y ++ ) {
14+ visited [ y ] = [ ]
15+ }
16+
17+ let dirs = [
18+ [ 1 , 0 ] ,
19+ [ - 1 , 0 ] ,
20+ [ 0 , - 1 ] ,
21+ [ 0 , 1 ] ,
22+ ]
23+
24+ // 验证是否能走入这个格子
25+ // 1. 范围不能越界
26+ // 2. 本轮递归中未访问过
27+ // 3. 格子的值不能为 0
28+ let isValid = ( y , x ) => {
29+ return (
30+ y >= 0 &&
31+ y < maxY &&
32+ x >= 0 &&
33+ x < maxX &&
34+ grid [ y ] [ x ] !== 0 &&
35+ ! visited [ y ] [ x ]
36+ )
37+ }
38+
39+ let maxGold = 0
40+ let helper = ( y , x , prevGold ) => {
41+ let val = grid [ y ] [ x ]
42+ let curGold = prevGold + val
43+ if ( curGold === 0 ) {
44+ return
45+ }
46+
47+ for ( let dir of dirs ) {
48+ let [ diffY , diffX ] = dir
49+ let nextY = y + diffY
50+ let nextX = x + diffX
51+ if ( isValid ( nextY , nextX ) ) {
52+ visited [ y ] [ x ] = true
53+ helper ( nextY , nextX , curGold )
54+ visited [ y ] [ x ] = false
55+ } else {
56+ // 走到尽头或者不符合条件的了
57+ maxGold = Math . max ( maxGold , curGold )
58+ }
59+ }
60+ }
61+
62+ for ( let y = 0 ; y < maxY ; y ++ ) {
63+ for ( let x = 0 ; x < maxX ; x ++ ) {
64+ helper ( y , x , 0 )
65+ }
66+ }
67+
68+ return maxGold
69+ }
You can’t perform that action at this time.
0 commit comments