Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

542. 01 Matrix 🌟🌟

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

BFS solution

Complexity:

Code

class Solution{
    vector<int> dirs = {0, 1, 0, -1, 0};

public:
    vector<vector<int>> updateMatrix(vector<vector<int>> &mat){
        int r = mat.size(), c = mat[0].size();

        queue<pair<int, int>> q;
        for (int i = 0; i < r; i++){
            for (int j = 0; j < c; j++){
                if (mat[i][j] == 0)
                    q.emplace(i, j);
                else
                    mat[i][j] = -1; // mark as not processed
            }
        }

        while (!q.empty()){
            auto [i, j] = q.front();
            q.pop();

            for (int k = 0; k < 4; k++){
                int nr = i + dirs[k], nc = j + dirs[k + 1];
                if (nr < 0 || nc < 0 || nr >= r || nc >= c || mat[nr][nc] != -1)
                    continue;
                mat[nr][nc] = mat[i][j] + 1;
                q.emplace(nr, nc);
            }
        }
        return mat;
    }
};

DP Solution

Complexity:

Code

class Solution{
public:
    vector<vector<int>> updateMatrix(vector<vector<int>> &mat){
        int r = mat.size(), c = mat[0].size(), total = r + c;

        for (int i = 0; i < r; i++){
            for (int j = 0; j < c; j++){
                if (mat[i][j] == 0) continue;
                int top = total, left = total;
                if (i - 1 >= 0) top = mat[i - 1][j];
                if (j - 1 >= 0) left = mat[i][j - 1];
                mat[i][j] = min(top, left) + 1;
            }
        }

        for (int i = r - 1; i >= 0; i--){
            for (int j = c - 1; j >= 0; j--){
                int bottom = total, right = total;
                if (i + 1 < r) bottom = mat[i + 1][j];
                if (j + 1 < c) right = mat[i][j + 1];
                mat[i][j] = min(mat[i][j], min(bottom, right) + 1);
            }
        }

        return mat;
    }
};

MUST READ: