intermediate · BFS · grid · shortest path · queue

Fewest steps across a walled grid

Problem

A robot sits in the top-left cell of a warehouse floor plan: 0 is free floor, 1 is a shelf. Each step moves it one cell up, down, left or right onto free floor. Return the fewest steps to reach the bottom-right cell, or −1 if it cannot be reached (including when the start or the goal is a shelf).

In the lab the plan is given row by row as one list, with its width; cell (r, c) is position r · width + c.

Constraints

  • 1 ≤ cells ≤ 30, width 1 to 8 (visualization limit)
  • cells are 0 or 1

Examples

plan = [[0, 0, 0], [1, 1, 0], [0, 0, 0]] → 4 — Along the top row, then down the right edge.

Show the solution

Breadth-first search from the start

BFS visits cells in order of distance, like a ripple spreading from the start. The first time the ripple touches a cell is along a shortest route.

Why it is correct

Invariant: the queue holds cells in non-decreasing order of distance, and every cell whose distance has been recorded got its true shortest distance. A cell discovered from a cell at distance d is at distance at most d + 1, and it cannot be closer, or it would have been discovered from a cell of distance < d, which left the queue earlier. So when the goal leaves the queue, its recorded distance is minimal. If the queue empties first, the goal is not connected to the start.

Complexity

Time O(rows · columns), extra space O(rows · columns). Each cell enters the queue at most once (it is marked when discovered) and looks at 4 neighbours when it leaves.

For contrast: Relax every cell from its neighbours repeatedly until no distance changes (Bellman–Ford on the grid). That costs O((rows · columns)²) time and O(rows · columns) space.

Edge cases

  • A 1 × 1 free grid: 0 steps.
  • Start or goal is a shelf: −1.
  • The goal is walled off: the queue empties, −1.

Common mistakes

  • Marking cells as visited when they are dequeued instead of enqueued, which lets a cell enter the queue several times.
  • Using DFS and returning the first path found.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class GridShortestPath
{
    private static readonly (int Dr, int Dc)[] Moves = [(-1, 0), (1, 0), (0, -1), (0, 1)];
 
    /// <summary>Fewest 4-directional steps over 0 cells from the top-left to the bottom-right cell, or -1. BFS: O(rows * cols).</summary>
    public static int Steps(int[][] grid)
    {
        int rows = grid.Length, cols = grid[0].Length;
        if (grid[0][0] == 1 || grid[rows - 1][cols - 1] == 1) return -1;
        var dist = new int[rows, cols];
        for (int r = 0; r < rows; r++)
            for (int c = 0; c < cols; c++) dist[r, c] = -1;
        dist[0, 0] = 0;
        var queue = new Queue<(int R, int C)>();
        queue.Enqueue((0, 0));
        while (queue.Count > 0)
        {
            var (r, c) = queue.Dequeue();
            if (r == rows - 1 && c == cols - 1) return dist[r, c];
            foreach (var (dr, dc) in Moves)
            {
                int nr = r + dr, nc = c + dc;
                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 0 && dist[nr, nc] == -1)
                {
                    dist[nr, nc] = dist[r, c] + 1; // first discovery = fewest steps (BFS order)
                    queue.Enqueue((nr, nc));
                }
            }
        }
        return -1;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/GridShortestPath.cs

from collections import deque
from collections.abc import Sequence
 
MOVES = ((-1, 0), (1, 0), (0, -1), (0, 1))
 
 
def steps(grid: Sequence[Sequence[int]]) -> int:
    """Fewest 4-directional steps over 0 cells from the top-left to the bottom-right cell, or -1. BFS: O(rows * cols)."""
    rows, cols = len(grid), len(grid[0])
    if grid[0][0] == 1 or grid[rows - 1][cols - 1] == 1:
        return -1
    dist = [[-1] * cols for _ in range(rows)]
    dist[0][0] = 0
    queue = deque([(0, 0)])
    while queue:
        r, c = queue.popleft()
        if r == rows - 1 and c == cols - 1:
            return dist[r][c]
        for dr, dc in MOVES:
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0 and dist[nr][nc] == -1:
                dist[nr][nc] = dist[r][c] + 1  # first discovery = fewest steps (BFS order)
                queue.append((nr, nc))
    return -1

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/grid_shortest_path.py

package dev.bekadan.dsa.problems;
 
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
 
public final class GridShortestPath {
    private GridShortestPath() {
    }
 
    private static final int[][] MOVES = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
 
    /** Fewest 4-directional steps over 0 cells from the top-left to the bottom-right cell, or -1. BFS: O(rows * cols). */
    public static int steps(int[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;
        if (grid[0][0] == 1 || grid[rows - 1][cols - 1] == 1) {
            return -1;
        }
        int[][] dist = new int[rows][cols];
        for (int[] row : dist) {
            Arrays.fill(row, -1);
        }
        dist[0][0] = 0;
        Deque<int[]> queue = new ArrayDeque<>();
        queue.add(new int[] {0, 0});
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int r = cell[0];
            int c = cell[1];
            if (r == rows - 1 && c == cols - 1) {
                return dist[r][c];
            }
            for (int[] m : MOVES) {
                int nr = r + m[0];
                int nc = c + m[1];
                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 0 && dist[nr][nc] == -1) {
                    dist[nr][nc] = dist[r][c] + 1; // first discovery = fewest steps (BFS order)
                    queue.add(new int[] {nr, nc});
                }
            }
        }
        return -1;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/GridShortestPath.java

#pragma once
 
#include <array>
#include <cstddef>
#include <queue>
#include <utility>
#include <vector>
 
namespace bekadan::dsa::problems {
 
namespace grid_shortest_path_detail {
inline constexpr std::array<std::array<int, 2>, 4> kMoves{{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}};
}  // namespace grid_shortest_path_detail
 
// Fewest 4-directional steps over 0 cells from the top-left to the bottom-right cell, or -1. BFS: O(rows * cols).
inline int grid_shortest_path(const std::vector<std::vector<int>>& grid) {
    const int rows = static_cast<int>(grid.size()), cols = static_cast<int>(grid[0].size());
    const auto cell = [&](int r, int c) { return grid[static_cast<std::size_t>(r)][static_cast<std::size_t>(c)]; };
    if (cell(0, 0) == 1 || cell(rows - 1, cols - 1) == 1) return -1;
    std::vector<std::vector<int>> dist(static_cast<std::size_t>(rows), std::vector<int>(static_cast<std::size_t>(cols), -1));
    dist[0][0] = 0;
    std::queue<std::pair<int, int>> queue;
    queue.emplace(0, 0);
    while (!queue.empty()) {
        const auto [r, c] = queue.front();
        queue.pop();
        const int here = dist[static_cast<std::size_t>(r)][static_cast<std::size_t>(c)];
        if (r == rows - 1 && c == cols - 1) return here;
        for (const auto& [dr, dc] : grid_shortest_path_detail::kMoves) {
            const int nr = r + dr, nc = c + dc;
            if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && cell(nr, nc) == 0 && dist[static_cast<std::size_t>(nr)][static_cast<std::size_t>(nc)] == -1) {
                dist[static_cast<std::size_t>(nr)][static_cast<std::size_t>(nc)] = here + 1;  // first discovery = fewest steps
                queue.emplace(nr, nc);
            }
        }
    }
    return -1;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/grid_shortest_path.hpp