|
| 1 | +package g0801_0900.s0864_shortest_path_to_get_all_keys; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | + |
| 5 | +public class Solution { |
| 6 | + class Status { |
| 7 | + int key; |
| 8 | + int i; |
| 9 | + int j; |
| 10 | + |
| 11 | + public Status(int key, int i, int j) { |
| 12 | + this.key = key; |
| 13 | + this.i = i; |
| 14 | + this.j = j; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + public int shortestPathAllKeys(String[] grid) { |
| 19 | + int success = 0; |
| 20 | + int startI = 0; |
| 21 | + int startJ = 0; |
| 22 | + int rows = grid.length; |
| 23 | + int cols = grid[0].length(); |
| 24 | + for (int i = 0; i < rows; i++) { |
| 25 | + for (int j = 0; j < cols; j++) { |
| 26 | + char c = grid[i].charAt(j); |
| 27 | + if (c >= 'A' && c <= 'F') { |
| 28 | + success |= 1 << (c - 'A'); |
| 29 | + } |
| 30 | + |
| 31 | + if (c == '@') { |
| 32 | + startI = i; |
| 33 | + startJ = j; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + int[][][] dist = new int[1 << 6][rows][cols]; |
| 38 | + for (int i = 0; i < dist.length; i++) { |
| 39 | + for (int j = 0; j < dist[0].length; j++) { |
| 40 | + for (int k = 0; k < dist[0][0].length; k++) { |
| 41 | + dist[i][j][k] = Integer.MAX_VALUE; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + LinkedList<Status> queue = new LinkedList<>(); |
| 46 | + queue.offer(new Status(0, startI, startJ)); |
| 47 | + dist[0][startI][startJ] = 0; |
| 48 | + int path = 0; |
| 49 | + int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; |
| 50 | + while (!queue.isEmpty()) { |
| 51 | + int size = queue.size(); |
| 52 | + while (size-- > 0) { |
| 53 | + Status status = queue.poll(); |
| 54 | + int key = status.key; |
| 55 | + int x = status.i; |
| 56 | + int y = status.j; |
| 57 | + if (key == success) { |
| 58 | + return path; |
| 59 | + } |
| 60 | + for (int[] dir : dirs) { |
| 61 | + int xx = x + dir[0]; |
| 62 | + int yy = y + dir[1]; |
| 63 | + if (xx >= 0 |
| 64 | + && xx < rows |
| 65 | + && yy >= 0 |
| 66 | + && yy < cols |
| 67 | + && grid[xx].charAt(yy) != '#') { |
| 68 | + int nextKey = key; |
| 69 | + char c = grid[xx].charAt(yy); |
| 70 | + if (c >= 'a' && c <= 'f') { |
| 71 | + nextKey = key | (1 << (c - 'a')); |
| 72 | + } |
| 73 | + |
| 74 | + if (c >= 'A' && c <= 'F' && (nextKey & (1 << (c - 'A'))) == 0) { |
| 75 | + continue; |
| 76 | + } |
| 77 | + if (path + 1 < dist[nextKey][xx][yy]) { |
| 78 | + dist[nextKey][xx][yy] = path + 1; |
| 79 | + queue.offer(new Status(nextKey, xx, yy)); |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + path++; |
| 85 | + } |
| 86 | + return -1; |
| 87 | + } |
| 88 | +} |
0 commit comments