【LeetCode】01矩阵

问题描述

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,1矩阵,找到矩阵中每个1距离0的最短路径,然后以矩阵的形式输出。典型的BFS(广度优先)问题求解,该题要注意溢出问题

代码块

class Solution {
private:
    vector<vector<int>>visit,d;
    queue<pair<int,int>>q;
    pair<int,int>p;
    int cur_i,cur_j;
    int width,height;
    void push_and_set(int row,int col){
        if(row>=0&&row<height&&col>=0&&col<width&&!visit[row][col]){
             d[row][col] = d[cur_i][cur_j] + 1;
             visit[row][col] = 1;
             q.push(make_pair(row,col));
        }
    }
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        height = matrix.size();
        width = matrix[0].size();
        visit = vector<vector<int>>(height,vector<int>(width));
        d = vector<vector<int>>(height,vector<int>(width));
        for(int i = 0; i < height; i++){
            for(int j = 0; j < width; j++){
                if(matrix[i][j] == 0){
                    q.push(make_pair(i,j));
                    visit[i][j]=1;
                    d[i][j] = 0;
                }
            }
        }
        while(!q.empty()){
            p = q.front();
            q.pop();
            cur_i = p.first;
            cur_j = p.second;
            push_and_set(cur_i - 1, cur_j);
            push_and_set(cur_i + 1, cur_j);
            push_and_set(cur_i, cur_j + 1);
            push_and_set(cur_i, cur_j - 1);
        }
        return d;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值