864. Shortest Path to Get All Keys
by Botao Xiao
864. Shortest Path to Get All Keys
Question
We are given a 2-dimensional grid. “.” is an empty cell, “#” is a wall, “@” is the starting point, (“a”, “b”, …) are keys, and (“A”, “B”, …) are locks.
We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can’t walk over a lock unless we have the corresponding key.
For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return the lowest number of moves to acquire all keys. If it’s impossible, return -1.
Example 1:
Input: ["@.a.#","###.#","b.A.B"]
Output: 8
Example 2:
Input: ["@..aA","..B#.","....b"]
Output: 6
Note:
- 1 <= grid.length <= 30
- 1 <= grid[0].length <= 30
- grid[i][j] contains only ‘.’, ‘#’, ‘@’, ‘a’-‘f’ and ‘A’-‘F’
- The number of keys is in [1, 6]. Each key has a different letter and opens exactly one lock.
Solution:
- Method 1: BFS
- we use a integer to represent current state |bit 31:16 x index| bits 15:8 y index | bits 7-0 key|
class Solution { public int shortestPathAllKeys(String[] grid) { int height = grid.length, width = grid[0].length(); char[][] g = new char[height][width]; int startX = -1, startY = -1; int expect = 0; for(int i = 0; i < height; i++){ char[] arr = grid[i].toCharArray(); for(int j = 0; j < width; j++){ g[i][j] = arr[j]; if(arr[j] == '@'){ startX = i; startY = j; }else if(arr[j] >= 'a' && arr[j] <= 'f'){ expect |= 1 << (arr[j] - 'a'); } } } Queue<Integer> q = new LinkedList<>(); //int[] records [x, y] int startState = (startX << 16) | (startY << 8) | 0; q.offer(startState); int step = -1; Set<Integer> visited = new HashSet<>(); while(!q.isEmpty()){ int size = q.size(); ++step; for(int i = 0; i < size; i++){ int cur = q.poll(); if((cur & (0b111111)) == expect) return step; if(visited.contains(cur)) continue; visited.add(cur); int tx = 0, ty = 0; int curX = (cur >> 16) & 0xFF, curY = (cur >> 8) & 0xFF; int curKey = cur & 0xFF; for(int d = 0; d < 4; d++){ tx = curX + dir[d][0]; ty = curY + dir[d][1]; if(tx >= 0 && tx < height && ty >= 0 && ty < width && g[tx][ty] != '#'){ if(isUpper(g[tx][ty]) && (cur & (1 << (g[tx][ty] - 'A'))) == 0) continue; int nextState = (tx << 16) | (ty << 8) | (!isLower(g[tx][ty]) ? curKey : (curKey | (1 << (g[tx][ty] - 'A')))); q.offer(nextState); } } } } return -1; } private boolean isUpper(char c){ return c >= 'A' && c <= 'F'; } private boolean isLower(char c){ return c >= 'a' && c <= 'f'; } }
- we use a integer to represent current state |bit 31:16 x index| bits 15:8 y index | bits 7-0 key|
Reference
Subscribe via RSS