01 Matrix

Description
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:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.

解题思路:这道题可以用BFS来解决,我们可能会想到对矩阵中的每一个非0的点进行BFS,即对点的上下左右四个相邻点进行访问,一旦访问到了值为0的点,BFS结束,输出进行BFS的次数就是该点到0点的最短距离。但使用这种方法的时间复杂度为O(m^2*n^2),如果矩阵的规模很大就会导致超时,所以需要更优的算法。现在我们改为对那些值为0的点进行BFS,先统计出所有值为0的点,存放在一个队列中,此时队列中的点到0点的距离全都为0(因为所有点都是0点),然后对队列中的点进行BFS操作,把访问到的点加入到队列中,同时让之前到0点的距离为0的点出队,这样操作完以后我们便得到了到0点距离为1的点,接下来重复上面的步骤,便可以算出矩阵中所有点到0点的距离。由于对每个点我们只访问了一次,所以时间复杂度为(m * n )。代码如下:

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int row = matrix.size();
        int col = matrix[0].size();
        vector<vector<int>> result(row, vector<int>(col, INT_MAX));
        vector<vector<int>> is_visited(row, vector<int>(col, 0));   //记录已访问的点
        queue<pair<int, int>> q;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] == 0) {
                    q.push(pair<int, int>(i, j));
                    is_visited[i][j] = 1;
                }
            }
        }

        int d = 0;    //到0点的距离
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                pair<int, int> temp = q.front();
                q.pop();
                int r = temp.first;
                int c = temp.second;
                result[r][c] = d;
                if (r - 1 >= 0 && !is_visited[r - 1][c]) {
                    q.push(pair<int, int>(r - 1, c));
                    is_visited[r - 1][c] = 1;
                }
                if (r + 1 < row && !is_visited[r + 1][c]) {
                    q.push(pair<int, int>(r + 1, c));
                    is_visited[r + 1][c] = 1;
                } 
                if (c - 1 >= 0 && !is_visited[r][c - 1]) {
                    q.push(pair<int, int>(r, c - 1));
                    is_visited[r][c - 1] = 1;
                } 
                if (c + 1 < col && !is_visited[r][c + 1]) {
                    q.push(pair<int, int>(r, c + 1));
                    is_visited[r][c + 1] = 1;
                } 
            }
            d++;
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值