KatInterview

542. 01 Matrix

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the shortest distance from each cell in a binary matrix to the nearest 0. The distance between adjacent cells (up, down, left, right) is 1. This is a classic shortest path problem on an unweighted grid.

Solution

01 Matrix in Python

from collections import deque

class Solution:
    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:
        m, n = len(mat), len(mat[0])
        
        # The result matrix, initialized with -1 for unvisited '1' cells.
        dist = [[-1] * n for _ in range(m)]
        # Queue for BFS, storing (row, col).
        q = deque()

        # Initialize the queue and distance matrix.
        # All '0' cells are the sources of the BFS, with distance 0.
        for r in range(m):
            for c in range(n):
                if mat[r][c] == 0:
                    dist[r][c] = 0
                    q.append((r, c))

        # Directions for neighbors: up, down, left, right.
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

        # Start the Multi-Source BFS.
        while q:
            r, c = q.popleft()

            # Explore neighbors.
            for dr, dc in directions:
                new_r, new_c = r + dr, c + dc

                # Check if the neighbor is valid and unvisited.
                if 0 <= new_r < m and 0 <= new_c < n and dist[new_r][new_c] == -1:
                    # Update distance and enqueue the neighbor.
                    dist[new_r][new_c] = dist[r][c] + 1
                    q.append((new_r, new_c))
            
        return dist

01 Matrix in Java

class Solution {
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        
        // The result matrix, initialized with -1 for unvisited '1' cells.
        int[][] dist = new int[m][n];
        // Queue for BFS, storing {row, col}.
        Queue<int[]> queue = new LinkedList<>();

        // Initialize the queue and distance matrix.
        // All '0' cells are the sources of the BFS, with distance 0.
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 0) {
                    dist[i][j] = 0;
                    queue.offer(new int[]{i, j});
                } else {
                    dist[i][j] = -1; // Mark as unvisited
                }
            }
        }

        // Directions for neighbors: up, down, left, right.
        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};

        // Start the Multi-Source BFS.
        while (!queue.isEmpty()) {
            int[] curr = queue.poll();
            int r = curr[0];
            int c = curr[1];

            // Explore neighbors.
            for (int i = 0; i < 4; i++) {
                int newR = r + dr[i];
                int newC = c + dc[i];

                // Check if the neighbor is valid and unvisited.
                if (newR >= 0 && newR < m && newC >= 0 && newC < n && dist[newR][newC] == -1) {
                    // Update distance and enqueue the neighbor.
                    dist[newR][newC] = dist[r][c] + 1;
                    queue.offer(new int[]{newR, newC});
                }
            }
        }

        return dist;
    }
}

01 Matrix in C++

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int m = mat.size();
        int n = mat[0].size();
        
        // The result matrix, initialized with -1 for unvisited '1' cells.
        vector<vector<int>> dist(m, vector<int>(n, -1));
        // Queue for BFS, storing {row, col}.
        queue<pair<int, int>> q;

        // Initialize the queue and distance matrix.
        // All '0' cells are the sources of the BFS, with distance 0.
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (mat[i][j] == 0) {
                    q.push({i, j});
                    dist[i][j] = 0;
                }
            }
        }

        // Directions for neighbors: up, down, left, right.
        int dr[] = {-1, 1, 0, 0};
        int dc[] = {0, 0, -1, 1};

        // Start the Multi-Source BFS.
        while (!q.empty()) {
            pair<int, int> curr = q.front();
            q.pop();
            int r = curr.first;
            int c = curr.second;

            // Explore neighbors.
            for (int i = 0; i < 4; ++i) {
                int new_r = r + dr[i];
                int new_c = c + dc[i];

                // Check if the neighbor is valid and unvisited.
                if (new_r >= 0 && new_r < m && new_c >= 0 && new_c < n && dist[new_r][new_c] == -1) {
                    // Update distance and enqueue the neighbor.
                    dist[new_r][new_c] = dist[r][c] + 1;
                    q.push({new_r, new_c});
                }
            }
        }

        return dist;
    }
};

01 Matrix in TypeScript

function updateMatrix(mat: number[][]): number[][] {
    const m = mat.length;
    const n = mat[0].length;

    // The result matrix, initialized with -1 for unvisited '1' cells.
    const dist: number[][] = Array(m).fill(0).map(() => Array(n).fill(-1));
    // Queue for BFS, storing [row, col].
    const queue: [number, number][] = [];

    // Initialize the queue and distance matrix.
    // All '0' cells are the sources of the BFS, with distance 0.
    for (let r = 0; r < m; r++) {
        for (let c = 0; c < n; c++) {
            if (mat[r][c] === 0) {
                dist[r][c] = 0;
                queue.push([r, c]);
            }
        }
    }

    // Directions for neighbors: up, down, left, right.
    const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
    let head = 0; // Use a pointer for queue head for performance

    // Start the Multi-Source BFS.
    while (head < queue.length) {
        const [r, c] = queue[head++];

        // Explore neighbors.
        for (const [dr, dc] of directions) {
            const newR = r + dr;
            const newC = c + dc;

            // Check if the neighbor is valid and unvisited.
            if (newR >= 0 && newR < m && newC >= 0 && newC < n && dist[newR][newC] === -1) {
                // Update distance and enqueue the neighbor.
                dist[newR][newC] = dist[r][c] + 1;
                queue.push([newR, newC]);
            }
        }
    }

    return dist;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.