#1091

Shortest Path in Binary Matrix

Medium
ArrayBreadth-First SearchMatrixBreadth-First SearchGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal approach uses Breadth-First Search (BFS) because it explores all possible paths level by level, ensuring that the first time we reach the bottom-right cell, it is through the shortest path.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue and add the starting cell (0, 0) along with the initial path length of 1.
  2. 2Step 2: While the queue is not empty, dequeue the front cell and explore all 8 possible directions.
  3. 3Step 3: For each valid neighboring cell (that is 0 and within bounds), enqueue it with an incremented path length and mark it as visited.
solution.py23 lines
1# Full working Python code
2from collections import deque
3from typing import List
4
5def shortestPathBinaryMatrix(grid: List[List[int]]) -> int:
6    n = len(grid)
7    if grid[0][0] == 1 or grid[n-1][n-1] == 1:
8        return -1
9
10    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
11    queue = deque([(0, 0, 1)])  # (x, y, path_length)
12    grid[0][0] = 1  # mark as visited
13
14    while queue:
15        x, y, path_length = queue.popleft()
16        if x == n - 1 and y == n - 1:
17            return path_length
18        for dx, dy in directions:
19            nx, ny = x + dx, y + dy
20            if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
21                grid[nx][ny] = 1  # mark as visited
22                queue.append((nx, ny, path_length + 1))
23    return -1

Complexity note: The time complexity is O(n²) because we may need to visit each cell in the grid once. The space complexity is O(n) due to the queue used for BFS, which can grow to the size of the grid in the worst case.

  • 1BFS is optimal for finding the shortest path in unweighted grids.
  • 2Marking cells as visited is crucial to avoid cycles and redundant checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.