Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Shortest path through a grid

Medium · Target 18 minutes · Graphs · Type asked atGoogleAmazonCitadel

A grid is a list of equal-length strings of '.' (open) and '#' (wall). Starting in the top-left cell, you may move up, down, left or right into open cells. Return the fewest moves needed to reach the bottom-right cell, or -1 if it cannot be reached. If either corner is a wall, return -1.

Examples

InputOutputWhy
grid = ["..#", ".#.", "..."]4Down, down, right, right: the wall in the middle forces the long way round.
grid = [".#", "#."]-1The corners are open but nothing connects them.
grid = ["."]0The start is the goal.

Constraints

  • 1 ≤ rows, cols ≤ 500
  • Every row has the same length
  • Cells are '.' or '#'

Hints

Hint 1

Each open cell is a node; each move is an edge of length 1. You want a shortest path in an unweighted graph.

Hint 2

Breadth-first search visits cells in order of their distance from the start, so the first time it reaches the goal is by a shortest path.

Hint 3

Process the queue one ring at a time (or store a distance per cell), and mark cells as seen when you enqueue them.

Where people lose marks

  • Using depth-first search, which finds a path but not the shortest one.
  • Marking cells when they are dequeued instead of enqueued: the same cell can then sit in the queue many times.
  • Using a list with pop(0) as the queue in Python, which makes each removal O(n). Use collections.deque.
  • Forgetting the cases where a corner is a wall, or the grid is a single cell.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.