跳转至

542.01 Matrix

Tags: Medium Depth-first Search Breadth-first Search

Links: https://leetcode.com/problems/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.

class Solution {
    int direction[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
    struct Node {
        int x, y;
        Node(int xEle, int yEle): x(xEle), y(yEle) {}
    };

public:
    vector<vector<int>> updateMatrix(vector<vector<int>> & matrix) {
        int m = matrix.size(), n = matrix[0].size();
        queue<Node> q;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (matrix[i][j] == 0) q.push(Node(i, j));
                else matrix[i][j] = INT_MAX;
            }
        }

        while (!q.empty()) {
            Node tmp = q.front(); q.pop();
            for (int i = 0; i < 4; ++i) {
                int nextRow = tmp.x + direction[i][0];
                int nextCol = tmp.y + direction[i][1];
                if (0 <= nextRow && nextRow < m && 0 <= nextCol && nextCol < n && matrix[nextRow][nextCol] > matrix[tmp.x][tmp.y] + 1) {
                    matrix[nextRow][nextCol] = matrix[tmp.x][tmp.y] + 1;
                    q.push(Node(nextRow, nextCol));
                }
            }
        }

        return matrix;
    }
};