770. Find the fewest moves through a grid with walls
Gridworlds show up in robotics, games and RL environments. Before training an agent, it helps to know the true shortest path so you can judge how close the agent gets.
Write shortest_path_grid(grid). grid is a list of equal-length strings. 'S' is the start, 'E' is the exit, '.' is open floor and '#' is a wall. You move one step up, down, left or right per move and cannot enter walls or leave the grid. Return the fewest moves from S to E, or -1 if E cannot be reached. There is exactly one S and one E.
def shortest_path_grid(grid)Example 1
Input: shortest_path_grid(['S.#', '..#', '#.E'])
Output: 4
Example 2
Input: shortest_path_grid(['S#E'])
Output: -1
Constraints
- 1 <= rows, cols <= 1,000
- Exactly one S and one E
Hint 1
Find S first.
Hint 2
Use collections.deque as the queue.
Hint 3
Store the distance with each queued cell.
Common mistakes
- Using depth-first search, which finds a path but not the shortest one.
- Marking cells visited on pop, which queues duplicates.
- Forgetting bounds checks at the grid edges.
Understand the idea
Modeling a grid as a graph means each open cell is a node and each legal move is an edge of weight 1. Breadth-first search then gives shortest paths in O(rows x cols) time. For ['S.#', '..#', '#.E'] the search reaches (1, 1) at distance 2, (2, 1) at 3 and E at 4. When moves have different costs, such as terrain or latency, you switch to Dijkstra's algorithm with a priority queue.