01 matrix

类别:BFS

难度:medium


题目描述

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.

input;

0 0 0
0 1 0
0 0 0
output:

0 0 0
0 1 0
0 0 0
input:

0 0 0
0 1 0
1 1 1
output:

0 0 0
0 1 0
1 2 1

算法分析


使用队列进行广度优先搜索。

(1)首先将所有的为0的位置放到队列中,并且为1的位置初始化为INT_MAX,

(2) 然后不断地取出队头的位置,

(3)对于队头位置的四个方向,判断从这个点出发到达其四个方向的相邻位置的距离是不是比相邻位置本身到达0的距离要小

(4)如果是的话,更新相邻位置的距离,并且将更新了距离的点的位置放到队列中

(5)当队列为空时,即得到了最终的结果。


代码实现

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int row = matrix.size();
        int col = matrix[0].size();
        vector<vector<int>> ans(row, vector<int> (col, INT_MAX));
        queue<pair<int,int>> que;
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                if (matrix[i][j] == 0) {
                    que.push({i,j});
                    ans[i][j] = 0;
                }
            }
        }
        pair<int,int> temp;
        int x, y, new_x, new_y;
        while (!que.empty()) {
            temp = que.front();
            que.pop();
            x = temp.first;
            y = temp.second;
            for (int i = 0; i < 4; ++i) {
                new_x = x;
                new_y = y;
                switch (i) {
                    case 0:
                        new_x++;
                        break;
                    case 1:
                        new_x--;
                        break;
                    case 2:
                        new_y++;
                        break;
                    case 3:
                        new_y--;
                        break;
                }
                if (new_x >= 0 && new_x < row && new_y >= 0 && new_y < col) {
                    if (ans[new_x][new_y] > ans[x][y] + 1) {
                        ans[new_x][new_y] = ans[x][y] + 1;
                        que.push({new_x, new_y});
                    }
                }
            }
        }
        return ans;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值