542. 01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1:

Input:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Output:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Example 2:

Input:
[[0,0,0],
 [0,1,0],
 [1,1,1]]

Output:
[[0,0,0],
 [0,1,0],
 [1,2,1]]

Note:

  1. The number of elements of the given matrix will not exceed 10,000.

  2. There are at least one 0 in the given matrix.

  3. The cells are adjacent in only four directions: up, down, left and right

// BFS
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { // time: O(m * n); space: O(m * n)
    int m = matrix.size(), n = matrix[0].size();
    vector<vector<int> > dirs({{-1, 0}, {1, 0}, {0, -1}, {0, 1}});
    queue<vector<int> > q;
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (matrix[i][j] == 0) q.push({i, j});
            else matrix[i][j] = numeric_limits<int>::max(); // mark unvisited 1 cells with INT_MAX
        }
    }
    while (!q.empty()) {
        auto t = q.front(); q.pop();
        for (const auto& dir : dirs) {
            int r = t[0] + dir[0], c = t[1] + dir[1];
            if (r < 0 || r >= m || c < 0 || c >= n || matrix[r][c] <= matrix[t[0]][t[1]] + 1) continue;
            matrix[r][c] = matrix[t[0]][t[1]] + 1;
            q.push({r, c});
        }
    }
    return matrix;
}
// DP
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { // time: O(m * n); space: O(m * n)
    int m = matrix.size(), n = matrix[0].size();
    vector<vector<int> > res(m, vector<int> (n, numeric_limits<int>::max() - 1));
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (matrix[i][j] == 0) res[i][j] = 0;
            else {
                if (i > 0) res[i][j] = min(res[i][j], res[i - 1][j] + 1);
                if (j > 0) res[i][j] = min(res[i][j], res[i][j - 1] + 1);
            }
        }
    }
    for (int i = m - 1; i >= 0; --i) {
        for (int j = n - 1; j >= 0; --j) {
            if (res[i][j] != 0 && res[i][j] != 1) {
                if (i < m - 1) res[i][j] = min(res[i][j], res[i + 1][j] + 1);
                if (j < n - 1) res[i][j] = min(res[i][j], res[i][j + 1] + 1);
            }
        }
    }
    return res;
}

Last updated

Was this helpful?