Advertisement

01 Matrix - LeetCode 542 Solution

01 Matrix - Complete Solution Guide

01 Matrix is LeetCode problem 542, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

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 <= 10 4 1 <= m * n <= 10 4 mat[i][j] is either 0 or 1 . There is at least one 0 in mat . Note: This question is the same as 17

Detailed Explanation

The problem asks us to find the distance to the nearest '0' for each cell in a given binary matrix (a matrix containing only 0s and 1s). The distance between two adjacent cells is defined as 1. The output should be a matrix of the same dimensions as the input, where each cell contains the distance to the nearest '0' in the original matrix. The constraints specify that the matrix dimensions are at most 100x100, and there is guaranteed to be at least one '0' in the input matrix.

Solution Approach

The provided solution uses a Breadth-First Search (BFS) algorithm. It first identifies all the '0' cells in the matrix and adds them to a queue. Then, it iterates through the matrix, replacing all '1' values with -1, effectively marking them as unvisited. The BFS then proceeds level by level, starting from the '0' cells. For each cell visited, it checks its neighbors (up, down, left, right). If a neighbor is a '1' (marked as -1), it calculates the distance to the nearest '0' as the current cell's distance plus 1, updates the neighbor's value in the matrix, and enqueues the neighbor for further exploration. This process continues until the queue is empty, ensuring that every cell has been visited and assigned the shortest distance to the nearest '0'.

Step-by-Step Algorithm

  1. Step 1: Initialize a queue and iterate through the input matrix `mat`.
  2. Step 2: For each cell, if its value is 0, add its coordinates to the queue. Otherwise, set its value to -1 to indicate it is unvisited.
  3. Step 3: While the queue is not empty, dequeue a cell (r, c).
  4. Step 4: For each of the four possible directions (up, down, left, right), calculate the coordinates of the neighboring cell (nr, nc).
  5. Step 5: Check if the neighboring cell is within the bounds of the matrix, and if its value is -1 (meaning it's a '1' and hasn't been visited yet).
  6. Step 6: If the neighboring cell satisfies the condition in step 5, update its value to `mat[r][c] + 1` (the distance from the current '0'), and enqueue its coordinates (nr, nc) for later processing.
  7. Step 7: Repeat steps 3-6 until the queue is empty. At this point, the matrix `mat` will contain the distances to the nearest '0' for each cell.
  8. Step 8: Return the modified matrix `mat`.

Key Insights

  • Insight 1: A Breadth-First Search (BFS) approach is suitable because we need to find the shortest path (distance) from each '1' to the nearest '0'. BFS explores outwards layer by layer.
  • Insight 2: Start the BFS from all the '0' cells simultaneously. This ensures that the distances calculated for the '1' cells are the minimum distances.
  • Insight 3: Mark unvisited '1' cells with a special value (-1) before the BFS to distinguish them from '0' cells and cells that have already been visited and assigned a distance. This prevents infinite loops.

Complexity Analysis

Time Complexity: O(m*n)

Space Complexity: O(m*n)

Topics

This problem involves: Array, Dynamic Programming, Breadth-First Search, Matrix.

Companies

Asked at: Accenture, DoorDash, Flipkart, Graviton.