864. Shortest Path to Get All Keys
BFS + 位运算
Input: grid = ["@.a..","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.Last updated
BFS + 位运算
Input: grid = ["@.a..","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.Last updated
Input: grid = ["@..aA","..B#.","....b"]
Output: 6Input: grid = ["@Aa"]
Output: -1class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
# get num of locks
n, m = len(grid), len(grid[0])
allk = 0
start = None
q = deque()
visited = set()
for i in range(n):
for j in range(m):
if grid[i][j] == '@':
start = (i,j)
elif grid[i][j].islower():
allk |= 1 << ord(grid[i][j].lower()) - ord('a')
q.append((start[0],start[1],0,0))
visited.add((start[0],start[1],0))
dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]
while q:
x, y, keys, steps = q.popleft()
if keys == allk:
return steps
for dx, dy in dir:
nx = x + dx
ny = y + dy
if 0 <= nx < n and 0 <= ny < m:
if grid[nx][ny] == '#':
continue
newk = keys #key也是状态之一
if 'a'<=grid[nx][ny]<='z':
newk = keys | 1 << ord(grid[nx][ny]) - ord('a')
elif 'A'<=grid[nx][ny]<='Z':
if not(keys & 1 << ord(grid[nx][ny]) - ord('A')):
continue
if (nx,ny,newk) not in visited:
q.append((nx, ny, newk, steps + 1))
visited.add((nx, ny, newk))
return -1