LeetCode 542. 01Matrix

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/86382030

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.

对全部的0 bfs 找1

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

        int dir[4][2] = {-1,0,1,0,0,-1,0,1};
        while (!q.empty()) {
            pair<int, int> head = q.front();
            q.pop();
            for (int k = 0; k < 4; k++) {
                int nx = head.first + dir[k][0], ny = head.second + dir[k][1];
                if (nx >= 0 && ny >= 0 && nx < n && ny < m && matrix[nx][ny] == 1) {
                    if (dist[nx][ny] > dist[head.first][head.second] + 1) {
                        dist[nx][ny] = dist[head.first][head.second] + 1;
                        q.push({ nx, ny });
                    }
                }
            }
        }
        return dist;
    }
};

dp
待补

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/86382030