|
| 1 | +package L0864; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Solution { |
| 6 | + |
| 7 | + public int shortestPathAllKeys(String[] grid) { |
| 8 | + Deque<int[]> queue = new ArrayDeque<>(); |
| 9 | + int keyCnt = 0; |
| 10 | + int row = grid.length, col = grid[0].length(); |
| 11 | + int[][][] dist = new int[row][col][1 << 10]; |
| 12 | + int[][] dir = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; |
| 13 | + for (int i = 0; i < row; i++) { |
| 14 | + for (int j = 0; j < col; j++) { |
| 15 | + Arrays.fill(dist[i][j], 0x3f3f3f3f); |
| 16 | + char c = grid[i].charAt(j); |
| 17 | + if (c == '@') { |
| 18 | + queue.add(new int[]{i, j, 0}); |
| 19 | + dist[i][j][0] = 0; |
| 20 | + } else if (Character.isLowerCase(c)) { |
| 21 | + keyCnt++; |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + while (!queue.isEmpty()) { |
| 26 | + int[] pos = queue.pollFirst(); |
| 27 | + int x = pos[0], y = pos[1], keyMask = pos[2],step = dist[x][y][keyMask]; |
| 28 | + for (int[] di : dir) { |
| 29 | + int nx = x + di[0]; |
| 30 | + int ny = y + di[1]; |
| 31 | + if (nx < 0 || nx >= row || ny < 0 || ny >= col) { |
| 32 | + continue; |
| 33 | + } |
| 34 | + char c = grid[nx].charAt(ny); |
| 35 | + // 如果是墙,则跳过 |
| 36 | + if (c == '#') { |
| 37 | + continue; |
| 38 | + } |
| 39 | + // 如果是锁,但是没有对应的钥匙,也跳过 |
| 40 | + if (Character.isUpperCase(c) && ((keyMask >> (c - 'A') & 1) == 0)) { |
| 41 | + continue; |
| 42 | + } |
| 43 | + int curKeyMask = keyMask; |
| 44 | + // 如果是钥匙,则扩充当前位置的钥匙数量 |
| 45 | + if (Character.isLowerCase(c)) { |
| 46 | + curKeyMask = curKeyMask | 1 << (c - 'a'); |
| 47 | + } |
| 48 | + // 如果获取了所有钥匙,则返回步数 |
| 49 | + if ((1 << keyCnt) - 1 == curKeyMask) { |
| 50 | + return step + 1; |
| 51 | + } |
| 52 | + // 如果是其他情况(空格),则继续行走,对应步数 + 1 |
| 53 | + if (step + 1 < dist[nx][ny][curKeyMask]) { |
| 54 | + dist[nx][ny][curKeyMask] = step + 1; |
| 55 | + queue.addLast(new int[]{nx, ny, curKeyMask}); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + return -1; |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | +} |
0 commit comments