542. 01 Matrix 题解

542. 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.


题目链接:542. 01 Matrix



算法描述:


             由题意知,给出一个 0 - 1 矩阵,我们将找到每个 1 与 0 的最短距离,返回一个结果矩阵。


        我们采用广度优先遍历 BFS 。构建一个队列 q ,对矩阵进行顺序遍历,如果发现 0 ,将其位置坐标放入队列中,否则,将其置为 -1(默认数) 。


        之后,我们从队列当中依次取出头元素,第一次取出时,它们表示矩阵中的 0 ,我们再利用 dis 数组可以求出它们的上下左右四个相邻元素的位置坐标,当这四个上下左右元素的位置满足条件(位置在矩阵内部,并且对应的值为 -1 ),我们对其赋值(表示距离它相邻的 0 元素位置加一),之后再将其放入队列中。这样,按照广度优先遍历的方法依次访问和更新矩阵中的值,直到队列中元素为空。


             返回结果矩阵。



代码:


class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        vector<vector<int>> ansMatrix = matrix;
        typedef pair<int,int> t;
        queue<t> q;
        t dis[4] = { t(-1,0), t(1,0), t(0,1) ,t(0,-1) };
        if(matrix.size() == 0 || matrix[0].size() == 0){
            return ansMatrix;
        }
        
        for (int i=0; i<matrix.size(); i++){
            for(int j=0; j<matrix[0].size(); j++){
                if(matrix[i][j]==0){
                    q.push(t(i,j));
                }
                else{
                    ansMatrix[i][j]=-1;
                }
            }
        }
        
        while(q.size() != 0){
            t temp = q.front();
            int x = temp.first;
            int y = temp.second;
            q.pop();
            for(int i=0; i<4; i++){
                int nx = x+dis[i].first;
                int ny = y+dis[i].second;
                if(nx>=0 && nx<matrix.size() && ny>=0 && ny<matrix[0].size() && ansMatrix[nx][ny] ==-1){
                    ansMatrix[nx][ny] = ansMatrix[x][y]+1;
                    q.push(t(nx,ny));
                }
            }
        }
        
        return ansMatrix;
        
    }
};
































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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值