algoadvance

  1. Could you please confirm the size range for the matrix? Are we considering a matrix with large dimensions (e.g., 1000x1000)?
  2. Should we assume that the matrix can contain only binary values (0 and 1)?
  3. Can we modify the input matrix, or do we need to maintain the original and return a new matrix?
  4. Is there a specific way you would like the distance to be measured (e.g., Manhattan distance)?

Strategy

We need to find the distance of the nearest 0 for each cell in a binary matrix. The straightforward approach could involve iterating over every cell and computing the distance to every zero, which would be quite inefficient. Instead, we can utilize a Breadth-First Search (BFS) approach to achieve a more efficient solution.

  1. Initialization:
    • Create a queue to perform BFS.
    • Initialize distances: Use a matrix to store distances, initializing the distance to zero for cells containing zero and to infinity (or a large number) for cells containing one.
  2. BFS Traversal:
    • For each cell containing zero, add its coordinates to the queue.
    • For each cell dequeued, update its neighboring cells (top, bottom, left, right) if we find a shorter path to a zero.
    • Continue until all the reachable cells are processed.

Time Complexity

Code

Here’s the implementation in Python:

from collections import deque

def updateMatrix(matrix):
    if not matrix or not matrix[0]:
        return []

    rows, cols = len(matrix), len(matrix[0])
    dist = [[float('inf')] * cols for _ in range(rows)]
    queue = deque()
    
    # Enqueue all 0 cells and set their distance to 0
    for r in range(rows):
        for c in range(cols):
            if matrix[r][c] == 0:
                dist[r][c] = 0
                queue.append((r, c))
    
    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    while queue:
        r, c = queue.popleft()
        for dr, dc in directions:
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols:
                if dist[nr][nc] > dist[r][c] + 1:
                    dist[nr][nc] = dist[r][c] + 1
                    queue.append((nr, nc))
    
    return dist

Explanation

  1. Initialization:
    • We create a distance matrix dist initialized to infinity.
    • We populate the queue with all the cells containing 0 and set their distances to 0 in the dist matrix.
  2. BFS Traversal:
    • For each cell, we dequeue and examine its valid neighbors (within bounds).
    • If the neighbor’s current distance is greater than the distance to the current cell plus one, we update the neighbor’s distance and enqueue it for further processing.

With this approach, we efficiently compute the distance of the nearest 0 for each cell in the matrix.

Try our interview co-pilot at AlgoAdvance.com