Shortest Path to Get All Keys LeetCode solution in Python
1class Solution:2def shortestPathAllKeys(self, grid: List[str]) -> int:34m = len(grid)5n = len(grid[0])6visited = set()78steps = 09q = deque([])10keyCt = 01112for i in range(m):13for j in range(n):14if grid[i][j] == "@":15q.append((i, j, ""))16elif grid[i][j].islower():17keyCt += 11819while q:20for _ in range(len(q)):21curr_x, curr_y, keys = q.popleft()22if (curr_x, curr_y, keys) in visited:23continue2425visited.add((curr_x, curr_y, keys))2627if len(keys) == keyCt:28return steps2930for x, y in ((0, 1), (1, 0), (-1, 0), (0, -1)):31nx = curr_x + x32ny = curr_y + y33if (34nx < 035or ny < 036or nx >= m37or ny >= n38or grid[nx][ny] == "#"39or (nx, ny, keys) in visited40):41continue4243curr = grid[nx][ny]44if curr in "abcdef" and curr not in keys:45q.append((nx, ny, keys + curr))46elif curr.isupper() and curr.lower() not in keys:47continue48else:49q.append((nx, ny, keys))50steps += 15152return -1