Skip to content

Commit ad030d8

Browse files
authored
Merge pull request chipbk10#91 from chipbk10/Graph
Solve Problem 864 - Shortest Path To Get All Keys
2 parents 8058b32 + 7fd03a0 commit ad030d8

File tree

3 files changed

+55
-4
lines changed

3 files changed

+55
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
### Trie:
1313
### Binary Search: [#](https://leetcode.com/discuss/interview-question/313216/)
1414
### Minimax: 913
15-
### Matrix: 1368, 1292
15+
### Matrix: 1368, 1292, 864
1616

1717
# Favorite:
1818

src/contest/ReadMe.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ public class ReadMe {
1818
// sliding window: 1208[v] 1040[!] 995[!]
1919
// linked-list: 1290[v] 1019[!] 876[v]
2020
// union-find: 1202[v] 924[v] 947[!]
21-
// heap: 1054[!] 882[!] 864
22-
// design: 1352[x] 1348[x] 705
23-
// bit manipulation: 1356[v] 1342[v] 1318
21+
// heap: 1054[!] 882[!] 864[x]
22+
// design: 1352[x] 1348[x] 705[v]
23+
// bit manipulation: 1356[v] 1342[v] 1318[v]
2424
// other: 913[x] 1288[v] 843
2525

2626

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package graph.bfs;
2+
3+
import java.util.HashSet;
4+
import java.util.LinkedList;
5+
import java.util.Queue;
6+
import java.util.Set;
7+
8+
public class Problem864_ShortestPathToGetAllKeys {
9+
10+
11+
// STILL WRONG
12+
public int shortestPathAllKeys(String[] A) {
13+
int m = A.length, n = A[0].length(), KEYS = 0;
14+
Set<Integer> seen = new HashSet<>();
15+
Queue<int[]> queue = new LinkedList<>();
16+
17+
for (int i = 0; i < m; i++) {
18+
for (int j = 0; j < n; j++) {
19+
char c = A[i].charAt(j);
20+
if (c == '@') {
21+
queue.offer(new int[] {i, j, 0});
22+
seen.add((i*m+j) * 127 + 0);
23+
}
24+
else if (c >= 'a' && c <= 'f') KEYS |= (1 << (c-'a'));
25+
}
26+
}
27+
28+
int dirs[][] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}, res = -1;
29+
while (!queue.isEmpty()) {
30+
res++;
31+
int size = queue.size();
32+
for (int k = 0; k < size; k++) {
33+
int e[] = queue.poll(), i = e[0], j = e[1], keys = e[2];
34+
for (int[] d : dirs) {
35+
int x = i + d[0], y = j + d[1];
36+
if (x < 0 || x >= m || y < 0 || y >= n) continue; // out of grid
37+
char c = A[x].charAt(y);
38+
if (seen.contains((x*m+y)*127 + keys)) continue; // visited
39+
if (c == '#') continue; // wall
40+
if (c >= 'A' && c <= 'F' && (keys & (1 << (c-'A'))) == 0) continue; // no key
41+
if (c >= 'a' && c <= 'f') keys |= (1 << (c-'a')); // update key
42+
if (keys == KEYS) return res;
43+
queue.offer(new int[] {x, y, keys});
44+
seen.add((x*m+y)*127 + keys);
45+
}
46+
}
47+
}
48+
49+
return -1; // not found
50+
}
51+
}

0 commit comments

Comments
 (0)