Approach

  Blog    |     January 29, 2026

To solve this problem, we need to find the shortest path from a starting cell (marked as 2) to a destination cell (marked as 3) in a grid. The grid may contain blocked cells (marked as 1) that cannot be traversed. The solution involves using Breadth-First Search (BFS) to explore all possible paths level by level, ensuring the shortest path is found efficiently.

  1. Problem Analysis: The grid consists of cells that can be empty (0), blocked (1), starting point (2), or destination (3). The goal is to navigate from the starting point to the destination using the shortest path, moving only up, down, left, or right.
  2. Intuition: BFS is suitable here because it explores all neighboring cells level by level, ensuring the first time we reach the destination, it is via the shortest path.
  3. Algorithm Selection: BFS is chosen for its ability to find the shortest path in an unweighted grid. We maintain a queue to process each cell and its neighbors, tracking the number of steps taken.
  4. Optimization: Using a visited set ensures each cell is processed only once, preventing redundant checks and infinite loops.
  5. Complexity Analysis: The algorithm runs in O(mn) time, where m and n are the grid dimensions, as each cell is processed at most once. The space complexity is also O(mn) for the visited set and queue.

Solution Code

from collections import deque
def shortest_path(grid):
    m = len(grid)
    n = len(grid[0])
    start = None
    dest = None
    for i in range(m):
        for j in range(n):
            if grid[i][j] == 2:
                start = (i, j)
            elif grid[i][j] == 3:
                dest = (i, j)
    if start is None or dest is None:
        return -1
    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    visited = [[False] * n for _ in range(m)]
    queue = deque()
    queue.append((start[0], start[1], 0))
    visited[start[0]][start[1]] = True
    while queue:
        r, c, steps = queue.popleft()
        if (r, c) == dest:
            return steps
        for dr, dc in directions:
            nr, nc = r + dr, c + dc
            if 0 <= nr < m and 0 <= nc < n:
                if not visited[nr][nc] and grid[nr][nc] != 1:
                    visited[nr][nc] = True
                    queue.append((nr, nc, steps + 1))
    return -1

Explanation

  1. Initialization: The grid dimensions are determined, and the start and destination positions are located by scanning the grid.
  2. BFS Setup: A queue is initialized with the starting position and step count 0. A visited matrix tracks processed cells to avoid revisiting.
  3. BFS Execution: The queue processes each cell by exploring its four neighbors (up, down, left, right). Valid neighbors (within bounds, not blocked, and not visited) are enqueued with an incremented step count.
  4. Termination: If the destination is reached, the current step count is returned. If the queue is exhausted without finding the destination, -1 is returned indicating no path exists.

This approach efficiently explores all possible paths in the grid, ensuring the shortest path is found using BFS, which is optimal for unweighted grid pathfinding.


Request an On-site Audit / Inquiry

SSL Secured Inquiry