Shortest Path to Get All Keys solution explained

Shortest Path to Get All Keys is a breadth-first search where the state is not just a cell but a cell plus the set of keys you hold, stored as a bitmask. Two visits to the same cell with different key sets are different states, because a new key can open a door you could not pass before. BFS over those states returns the first depth at which the mask is full, or -1 if it never fills.

By Published 9 min read

The problem in plain words

You are given a grid of characters. The @ marks where you start, # is a wall, and . is open floor. Lowercase letters a to f are keys and the matching uppercase letters A to F are locked doors. Each step moves you one cell up, down, left or right. Walking onto a key picks it up. You can walk through a door only if you already hold its key. Return the fewest steps needed to hold every key in the grid, or -1 if you cannot. You do not need to open every door, and you do not need to end anywhere in particular.

Small grids invented for this page (rows separated by slashes)
GridAnswerWhat happens
@.a / ##. / b.A6Two steps to key a, then down through door A and left to key b in four more
a.@.B / ###.# / b...A10Grab a first (2 steps), then walk all the way around to b (8). Doors A and B are dead ends you never need
b..@.a.....c14Go left to b first (3), then right to c (11). Heading to the nearest key a first costs 18
@Aa-1Key a sits behind its own door, so it can never be reached
Small grids invented for this page (rows separated by slashes). Scroll sideways on a small screen.

The third grid is the one to remember. Walking to the closest key first is a natural guess, and it is wrong. The search has to compare whole routes, which is why a greedy plan does not work here.

Why a normal grid BFS is not enough

In an ordinary maze, a visited set over cells is correct because coming back to a cell can never help. Here it can. Picture a corridor where key a is to the left and door A blocks the way to the right. You walk left, take the key, and must walk back through the exact cells you already visited. With a cell-only visited set, the return trip is forbidden and the search wrongly reports -1.

The fix is to widen the state. What matters about your situation is where you stand and which keys you hold. Two visits that agree on both are truly the same, and the second one can be skipped. Two visits that differ in keys are different situations. With at most six keys, the key set fits in a six-bit integer: bit i is set when key chr(97 + i) is held.

Slow approach: try every key order

Any successful walk picks up the keys in some order. So you can try all K! orders, and for each one run a BFS from the start to the first key, then to the second, and so on, letting each leg pass only the doors whose keys are already held. The cheapest total over all orders is the answer. It is correct and easy to explain, and it makes a good test oracle, but it runs K! · K grid searches. Six keys means 720 orders times six searches each, and it repeats a lot of identical work that the bitmask search shares.

Main approach: BFS over cell and key mask

  1. Scan the gridRecord the start cell and build the target mask with one bit for every key that appears.
  2. Seed the queuePush (start row, start column, mask 0, distance 0) and mark that triple seen.
  3. Expand four neighborsSkip cells off the grid, walls, and doors whose bit is not in the current mask. If the neighbor is a key, OR its bit into the mask.
  4. Deduplicate on the tripleOnly push (row, column, new mask) if that exact triple has not been seen.
  5. Stop on a full maskThe first popped state whose mask equals the target is the answer, because BFS pops states in order of distance.
from collections import deque

def fewest_steps_all_keys(grid):
    rows, cols = len(grid), len(grid[0])
    full = 0
    for r in range(rows):
        for c in range(cols):
            ch = grid[r][c]
            if ch == "@":
                sr, sc = r, c
            elif ch.islower():
                full |= 1 << (ord(ch) - ord("a"))
    seen = {(sr, sc, 0)}
    queue = deque([(sr, sc, 0, 0)])
    while queue:
        r, c, keys, d = queue.popleft()
        if keys == full:
            return d
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if not (0 <= nr < rows and 0 <= nc < cols):
                continue
            ch = grid[nr][nc]
            if ch == "#":
                continue
            if ch.isupper() and not keys & (1 << (ord(ch) - ord("A"))):
                continue
            nkeys = keys | (1 << (ord(ch) - ord("a"))) if ch.islower() else keys
            if (nr, nc, nkeys) not in seen:
                seen.add((nr, nc, nkeys))
                queue.append((nr, nc, nkeys, d + 1))
    return -1
Python: BFS over (row, column, keys) with a set of seen triples.
function fewestStepsAllKeys(grid) {
  const rows = grid.length, cols = grid[0].length;
  let sr = 0, sc = 0, full = 0;
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; c++) {
      const ch = grid[r][c];
      if (ch === "@") { sr = r; sc = c; }
      else if (ch >= "a" && ch <= "f") full |= 1 << (ch.charCodeAt(0) - 97);
    }
  const seen = new Uint8Array(rows * cols * 64);
  seen[(sr * cols + sc) * 64] = 1;
  const queue = [[sr, sc, 0, 0]];
  for (let head = 0; head < queue.length; head++) {
    const [r, c, keys, d] = queue[head];
    if (keys === full) return d;
    for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
      if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
      const ch = grid[nr][nc];
      if (ch === "#") continue;
      if (ch >= "A" && ch <= "F" && !(keys & (1 << (ch.charCodeAt(0) - 65)))) continue;
      const nkeys = ch >= "a" && ch <= "f" ? keys | (1 << (ch.charCodeAt(0) - 97)) : keys;
      const id = (nr * cols + nc) * 64 + nkeys;
      if (!seen[id]) {
        seen[id] = 1;
        queue.push([nr, nc, nkeys, d + 1]);
      }
    }
  }
  return -1;
}
JavaScript: the seen set is a flat byte array indexed by cell times 64 plus mask.

The JavaScript version walks the queue with a head index instead of calling shift, which would make each pop linear. The flat byte array sized R · C · 64 takes about 58 kilobytes for a 30 by 30 grid, far cheaper than a Set of strings.

Complexity

R rows, C columns, K keys (K is at most 6)
ApproachTimeSpace
Every key order plus BFS legsO(K! · K · R · C)O(R · C) per leg
BFS over (cell, mask)O(R · C · 2^K)O(R · C · 2^K)
R rows, C columns, K keys (K is at most 6). Scroll sideways on a small screen.

Each state is pushed at most once and has four neighbors, so the bitmask search does constant work per state. The 2^K factor is the price of remembering which keys you hold, and it stays small only because K is capped. Say that limit out loud; it is what makes the approach acceptable.

Edge cases to test

  • No keys at all: the start state already has a full mask of 0, so the answer is 0.
  • A key behind its own door, which must give -1 instead of looping.
  • A route that has to backtrack through visited cells after picking up a key.
  • Doors with no matching key in the grid. They act as walls for the whole search.
  • A single-row grid, where every move is left or right and greedy choices are easy to test.
  • The start cell surrounded by walls.

Common mistakes

  • A visited set keyed on cells only, which blocks legitimate return trips.
  • Building a full mask of six bits when the grid only has three keys, so the target is never reached.
  • Updating the mask after the dedupe check instead of before it, which merges states that should stay separate.
  • Checking the door against the key mask of the new cell instead of the keys already held.
  • Using a greedy nearest-key plan, which fails on the third example.
  • Calling queue.shift() in JavaScript on large grids, turning a linear search into a quadratic one.

Talking through it

Fictional example

Explaining why the state needs a mask
Candidate
Standard BFS on cells won't work, because after I pick up a key I may need to retrace my steps to reach a door. Coming back to a cell with more keys is genuinely new progress.
Candidate
So my state is row, column, and the keys I hold. There are at most six keys, so a six-bit mask fits, and the number of states is R times C times 64.
Interviewer
And when do you stop?
Candidate
The first time I pop a state whose mask has every key bit set. BFS order means that distance is the minimum.

The same cell-plus-mask trick shows up on a general graph in Shortest Path Visiting All Nodes, where the mask records visited nodes instead of keys. If you want the simpler version where the visiting order is fixed in advance, compare it with Cut Off Trees for Golf Event. The next problem in this set, Minimum Knight Moves, drops the grid walls entirely and uses symmetry to bound the search instead.

Rehearsing with Natively

Grid problems with extra state are easy to misread, so it helps to rehearse them aloud. In a practice session Natively can read the prompt from a screenshot and outline a state design, which you can check against your own once you have committed to it. Its on-device transcript of the mock then lets you confirm you explained the mask before coding. See an AI interview assistant for the details.

Questions people ask

How do you solve Shortest Path to Get All Keys?

Run BFS where each state is the row, the column and a bitmask of keys held. A door is passable only if its bit is set, stepping on a key sets its bit, and the first state with every key bit set gives the answer.

Why not use a normal visited set on cells?

After picking up a key you often need to walk back through cells you already visited to reach a door. Those return trips are new states because the key set changed, so the visited set must include the mask.

What is the complexity of the bitmask BFS?

O(R · C · 2^K) time and space for an R by C grid with K keys. K is at most six, so the mask adds a factor of at most 64.

Does walking to the nearest key first work?

No. A greedy nearest-key plan can lead you away from the cheapest overall route, so the search has to compare whole routes, which the BFS does.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP