File tree 1 file changed +8
-7
lines changed
scripts/algorithms/S/Shortest Path Visiting All Nodes
1 file changed +8
-7
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 17 ms (Top 78.04%) | Memory: 46.7 MB (Top 69.44%)
1
2
class Solution {
2
3
class Pair {
3
4
int i ;
@@ -13,15 +14,15 @@ public int shortestPathLength(int[][] graph) {
13
14
boolean[currentNode][steps]
14
15
*/
15
16
int n = graph .length ;
16
-
17
+
17
18
// 111....1, 1<< n - 1
18
19
int allVisited = (1 << n ) - 1 ;
19
-
20
+
20
21
boolean [][] visited = new boolean [n ][1 << n ];
21
22
Queue <Pair > q = new LinkedList <>();
22
23
for (int i = 0 ; i < n ; i ++) {
23
24
if (1 << i == allVisited ) return 0 ;
24
- visited [i ][1 << i ] = true ;
25
+ visited [i ][1 << i ] = true ;
25
26
q .offer (new Pair (i , 1 << i ));
26
27
}
27
28
int step = 0 ;
@@ -30,18 +31,18 @@ public int shortestPathLength(int[][] graph) {
30
31
for (int i = 0 ; i < size ; i ++) {
31
32
Pair p = q .poll ();
32
33
int [] edges = graph [p .i ];
33
-
34
+
34
35
for (int t : edges ) {
35
36
int path = p .path | (1 << t );
36
37
if (path == allVisited ) return step + 1 ;
37
38
if (!visited [t ][path ]) {
38
39
visited [t ][path ] = true ;
39
- q .offer (new Pair (t , path ));
40
- }
40
+ q .offer (new Pair (t , path ));
41
+ }
41
42
}
42
43
}
43
44
step ++;
44
45
}
45
46
return step ;
46
47
}
47
- }
48
+ }
You can’t perform that action at this time.
0 commit comments