File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
shortest-path-to-get-all-keys Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -45,6 +45,8 @@ Step 2. Add the dependency
45
45
46
46
<summary >展开查看</summary >
47
47
48
+ https://leetcode.cn/problems/shortest-path-to-get-all-keys
49
+
48
50
https://leetcode.cn/problems/removing-minimum-and-maximum-from-array
49
51
50
52
https://leetcode.cn/problems/largest-plus-sign
Original file line number Diff line number Diff line change
1
+ export default function shortestPathAllKeys ( g : string [ ] ) : number {
2
+ const dirs = [
3
+ [ 1 , 0 ] ,
4
+ [ - 1 , 0 ] ,
5
+ [ 0 , 1 ] ,
6
+ [ 0 , - 1 ] ,
7
+ ] ;
8
+ const n = g . length ,
9
+ m = g [ 0 ] . length ;
10
+ let cnt = 0 ;
11
+ const dist = new Array < Array < Array < number > > > ( ) ;
12
+ for ( let i = 0 ; i < n ; i ++ ) {
13
+ dist [ i ] = new Array < Array < number > > ( m ) ;
14
+ for ( let j = 0 ; j < m ; j ++ ) {
15
+ dist [ i ] [ j ] = new Array < number > ( 1 << 10 ) . fill ( Infinity ) ;
16
+ }
17
+ }
18
+ const d : number [ ] [ ] = [ ] ;
19
+ for ( let i = 0 ; i < n ; i ++ ) {
20
+ for ( let j = 0 ; j < m ; j ++ ) {
21
+ if ( g [ i ] [ j ] == "@" ) {
22
+ d . push ( [ i , j , 0 ] ) ;
23
+ dist [ i ] [ j ] [ 0 ] = 0 ;
24
+ } else if ( g [ i ] [ j ] >= "a" && g [ i ] [ j ] <= "z" ) cnt ++ ;
25
+ }
26
+ }
27
+ while ( d . length > 0 ) {
28
+ const info = d . shift ( ) as [ number , number , number ] ;
29
+ const x = info [ 0 ] ,
30
+ y = info [ 1 ] ,
31
+ cur = info [ 2 ] ,
32
+ step = dist [ x ] [ y ] [ cur ] ;
33
+ for ( const di of dirs ) {
34
+ const nx = x + di [ 0 ] ,
35
+ ny = y + di [ 1 ] ;
36
+ if ( nx < 0 || nx >= n || ny < 0 || ny >= m ) continue ;
37
+ const c = g [ nx ] [ ny ] ;
38
+ if ( c == "#" ) continue ;
39
+ if (
40
+ "A" <= c &&
41
+ c <= "Z" &&
42
+ ( ( cur >> ( c . charCodeAt ( 0 ) - "A" . charCodeAt ( 0 ) ) ) & 1 ) == 0
43
+ )
44
+ continue ;
45
+ let ncur = cur ;
46
+ if ( "a" <= c && c <= "z" ) {
47
+ ncur |= 1 << ( c . charCodeAt ( 0 ) - "a" . charCodeAt ( 0 ) ) ;
48
+ }
49
+ if ( ncur == ( 1 << cnt ) - 1 ) return step + 1 ;
50
+ if ( step + 1 >= dist [ nx ] [ ny ] [ ncur ] ) continue ;
51
+ d . push ( [ nx , ny , ncur ] ) ;
52
+ dist [ nx ] [ ny ] [ ncur ] = step + 1 ;
53
+ }
54
+ }
55
+ return - 1 ;
56
+ }
You can’t perform that action at this time.
0 commit comments