Skip to main content

01 Matrix - Video Solutions

MediumArrayDynamic ProgrammingBreadth-First SearchMatrix

Leetcode 542. 01 Matrix - Python

HelmyCodeCamp
10:2526,344 views
10 video solutions available

01 Matrix - Video Solution

Watch 10 video solutions for 01 Matrix, a medium level problem involving Array, Dynamic Programming, Breadth-First Search. This walkthrough by HelmyCodeCamp has 26,344 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.

Problem Statement

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two cells sharing a common edge is 1.

 

Example 1:

Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]

Example 2:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.
  • There is at least one 0 in mat.

 

Note: This question is the same as 1765: https://leetcode.com/problems/map-of-highest-peak/

Read full problem with examples

Approach Overview

Problem Overview: You get an m x n binary matrix containing only 0 and 1. For every cell containing 1, compute the distance to the nearest 0. Distance is measured using 4-directional moves (up, down, left, right). The result is another matrix where each cell stores the shortest distance to a zero.

Approach 1: Breadth-First Search (Multi-Source BFS) (Time: O(m*n), Space: O(m*n))

This problem becomes straightforward once you flip the perspective. Instead of starting BFS from every 1, start from every 0 simultaneously. Push all zero cells into a queue and run a multi-source Breadth-First Search. Each expansion updates neighboring cells with distance current + 1. Because BFS explores level by level, the first time a cell is reached guarantees the shortest path to a zero. Use a queue and iterate through the grid once to initialize it. Then repeatedly pop cells, check their four neighbors, and update distances if they haven't been assigned yet. Each cell enters the queue at most once, giving linear time complexity.

This approach works well because BFS naturally computes shortest paths in an unweighted grid. Since all edges have equal cost (1 step), BFS guarantees minimal distance without extra bookkeeping. For grid shortest-path problems involving nearest targets, multi-source BFS is often the cleanest and most interview-friendly pattern. The grid itself can store distances, so only a queue is required for traversal.

Approach 2: Dynamic Programming Two-Pass Scan (Time: O(m*n), Space: O(1) extra)

The same result can be computed using Dynamic Programming with two directional passes. Initialize a distance matrix with a large value for cells containing 1 and 0 for zero cells. First pass: iterate top-left to bottom-right. For each cell, check top and left neighbors and update the distance using min(current, neighbor + 1). Second pass: iterate bottom-right to top-left and check bottom and right neighbors. These two passes propagate the shortest distance information across the grid.

The key insight is that the shortest path to a zero must come from one of the four directions. Splitting the updates into two directional sweeps ensures all possibilities are covered. This method avoids a queue and works purely with iterative updates over the matrix. Time complexity remains linear because each cell is processed a constant number of times.

Recommended for interviews: Multi-source BFS is the approach most interviewers expect. It demonstrates understanding of grid traversal and shortest-path patterns using BFS. The dynamic programming solution is equally optimal but slightly less intuitive unless you already recognize the two-pass DP pattern used in grid distance problems.

Complexity Analysis

ApproachTimeSpaceWhen to Use
Multi-Source BFSO(m*n)O(m*n)Best general solution for shortest distance in grids; very intuitive in interviews
Dynamic Programming Two-PassO(m*n)O(1) extraWhen avoiding queue-based traversal or optimizing memory usage