File tree Expand file tree Collapse file tree 3 files changed +38
-1
lines changed
shortest-path-to-get-all-keys
shortest-path-visiting-all-nodes Expand file tree Collapse file tree 3 files changed +38
-1
lines changed Original file line number Diff line number Diff line change @@ -45,6 +45,8 @@ Step 2. Add the dependency
4545
4646<summary >展开查看</summary >
4747
48+ https://leetcode.cn/problems/shortest-path-visiting-all-nodes
49+
4850https://leetcode.cn/problems/shortest-path-to-get-all-keys
4951
5052https://leetcode.cn/problems/removing-minimum-and-maximum-from-array
Original file line number Diff line number Diff line change @@ -40,8 +40,9 @@ export default function shortestPathAllKeys(g: string[]): number {
4040 "A" <= c &&
4141 c <= "Z" &&
4242 ( ( cur >> ( c . charCodeAt ( 0 ) - "A" . charCodeAt ( 0 ) ) ) & 1 ) == 0
43- )
43+ ) {
4444 continue ;
45+ }
4546 let ncur = cur ;
4647 if ( "a" <= c && c <= "z" ) {
4748 ncur |= 1 << ( c . charCodeAt ( 0 ) - "a" . charCodeAt ( 0 ) ) ;
Original file line number Diff line number Diff line change 1+ function shortestPathLength ( graph : number [ ] [ ] ) {
2+ const n = graph . length ;
3+ const queue : number [ ] [ ] = [ ] ;
4+ const seen : boolean [ ] [ ] = new Array ( n )
5+ . fill ( 0 )
6+ . map ( ( ) => new Array ( 1 << n ) . fill ( false ) ) ;
7+ for ( let i = 0 ; i < n ; ++ i ) {
8+ queue . push ( [ i , 1 << i , 0 ] ) ;
9+ seen [ i ] [ 1 << i ] = true ;
10+ }
11+
12+ let ans = 0 ;
13+ while ( queue . length ) {
14+ const tuple = queue . shift ( ) as [ number , number , number ] ;
15+ const u = tuple [ 0 ] ,
16+ mask = tuple [ 1 ] ,
17+ dist = tuple [ 2 ] ;
18+ if ( mask === ( 1 << n ) - 1 ) {
19+ ans = dist ;
20+ break ;
21+ }
22+ // 搜索相邻的节点
23+ for ( const v of graph [ u ] ) {
24+ // 将 mask 的第 v 位置为 1
25+ const maskV = mask | ( 1 << v ) ;
26+ if ( ! seen [ v ] [ maskV ] ) {
27+ queue . push ( [ v , maskV , dist + 1 ] ) ;
28+ seen [ v ] [ maskV ] = true ;
29+ }
30+ }
31+ }
32+ return ans ;
33+ }
34+ export default shortestPathLength ;
You can’t perform that action at this time.
0 commit comments