Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8 directions, or −1.

Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8 directions, or −1.
from collections import deque
def sp(g):
    n = len(g)
    if g[0][0] or g[n-1][n-1]: return -1
    q, seen = deque([(0, 0, 1)]), {(0, 0)}
    while q:
        r, c, d = q.popleft()
        if (r, c) == (n - 1, n - 1): return d
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < n and not g[nr][nc] and (nr, nc) not in seen:
                    seen.add((nr, nc)); q.append((nr, nc, d + 1))
    return -1
print(sp([[0, 0, 0], [1, 1, 0], [1, 1, 0]]), sp([[0, 1], [1, 0]]), sp([[1, 0], [0, 0]]))
What is printed?
  1. A. 4 2 -1
  2. B. 5 2 -1
  3. C. 4 -1 -1
  4. D. 3 2 -1

Correct answer: A. 4 2 -1

BFS counts cells: (0,0) → (0,1) → (1,2) → (2,2) is 4 cells using one diagonal. In the 2 × 2 grid the diagonal move gives 2. A blocked start returns −1 immediately. Marking cells on enqueue keeps it O(n²).

More Coding Interview Problems questions

Exams that ask this topic