Leetcode 542: 01 Matrix

grid47
grid47
Exploring patterns and algorithms
Sep 13, 2024 7 min read

A matrix where cells of 1s and 0s are arranged, with the shortest distance for 1s to 0s glowing softly.
Solution to LeetCode 542: 01 Matrix Problem

Given an m x n binary matrix, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.
Problem
Approach
Steps
Complexity
Input: You are given a binary matrix of size m x n where each cell is either 0 or 1.
Example: Input: mat = [[1,1,1],[1,0,1],[1,1,1]]
Constraints:
• 1 <= m, n <= 10^4
• 1 <= m * n <= 10^4
• mat[i][j] is either 0 or 1.
• There is at least one 0 in mat.
Output: Return a matrix where each element represents the distance to the nearest 0.
Example: Output: [[1,1,1],[1,0,1],[1,1,1]]
Constraints:
• The output matrix will have the same dimensions as the input matrix.
Goal: Find the nearest 0 for each cell and compute the distance.
Steps:
• Initialize a queue and add all positions of the zeros in the matrix.
• Start from the zeros and use a breadth-first search (BFS) to propagate the distance to all other cells.
• For each cell, update its distance as the shortest distance from a 0.
Goal: The matrix contains only 0s and 1s, and there is at least one 0 in the matrix.
Steps:
• The matrix has at most 10^4 elements.
Assumptions:
• The matrix is valid and contains at least one 0.
• The matrix can be large, so the solution should be efficient.
Input: Input: mat = [[1,1,1],[1,0,1],[1,1,1]]
Explanation: The nearest 0 to any 1 in the matrix is found by calculating the shortest path in terms of adjacency. The matrix will be updated with the distances to the nearest 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus