Breadth-First Search
01-Matrix
DESCRIPTION (credit Leetcode.com)
You are given an m x n binary matrix grid where each cell contains either a 0 or a 1.
Write a function that returns a matrix of the same dimensions where each cell contains the distance to the nearest 0 in the original matrix. The distance between two adjacent cells is 1. If there is no 0 in the grid, return -1 for each cell.
Example 1:
mat = [ [1, 0, 1], [0, 1, 0], [1, 1, 1], ]
Output:
[ [1, 0, 1], [0, 1, 0], [1, 2, 1], ]
Explanation
[
[1, 0, 1],
[0, 1, 0],
[1, 1, 1],
]Step 1: Initialize the Queue
# the coordinates of cells with value 0
queue = [ (0, 1), (1, 0), (1, 2) ]# setting the distances of cells with value 0 to 0 in the output grid
output = [
[-1, 0, -1],
[0, -1, 0],
[-1, -1, -1],
]Step 2: Perform BFS Traversal (Distance 1)
queue = [ (0, 0), (0, 2), (1, 1), (2, 0), (2, 2) ]output = [
[1, 0, 1],
[0, 1, 0],
[1, -1, 1],
]Step 3: Perform BFS Traversal (Distance 2)
queue = [ (2, 1) ]output = [
[1, 0, 1],
[0, 1, 0],
[1, 2, 1],
]Step 4: Perform BFS Traversal (Distance 3)
queue = []output = [
[1, 0, 1],
[0, 1, 0],
[1, 2, 1],
]Step 5: Return the Output Grid
[
[1, 0, 1],
[0, 1, 0],
[1, 2, 1],
]Solution
from collections import dequeclass Solution:def updateMatrix(self, mat):rows, cols = len(mat), len(mat[0])output = [[-1] * cols for _ in range(rows)]queue = deque()# Step 1: Initialize the queue with all the 0 cells# set their distance to 0 in the output gridfor r in range(rows):for c in range(cols):if mat[r][c] == 0:queue.append((r, c))output[r][c] = 0directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]# Step 2: Perform BFS traversaldistance = 1while queue:for _ in range(len(queue)):r, c = queue.popleft()for dr, dc in directions:nr, nc = r + dr, c + dcif 0 <= nr < rows and 0 <= nc < cols:if output[nr][nc] == -1:output[nr][nc] = distancequeue.append((nr, nc))distance += 1# Step 5: Return the output gridreturn output
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the input matrix. We visit each cell at most once, and each cell is enqueued at most once.
Space Complexity: O(m * n) where m is the number of rows and n is the number of columns in the input matrix. The space required for the output matrix is O(m * n), and the space required for the queue can be at most O(m * n) in the worst case (e.g., when all cells are 0 and are enqueued at the start).
Mark as read
Your account is free and you can post anonymously if you choose.