leetcode-542. 01 Matrix

本文介绍了一种算法,用于计算给定0和1组成的矩阵中每个元素到最近的0的距离。该算法通过迭代检查所有距离值加一的位置,并确保这些位置至少有一个相邻的更近距离值。

题目

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.

给定一个由0和1组成的矩阵,找到每个单元和最近的0的距离。

两个相邻单元的距离是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.


代码


#include <vector>
#include <iostream>  
using namespace std;


class Solution {
public:
    bool valid(vector<vector<int>> &matrix,int rows,int cols,int i,int j,int val){
        return i>=0&&i<rows&&j>=0&&j<cols&&matrix[i][j] == val;
    }
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        if(rows ==0 ){return matrix;}
        int cols = matrix[0].size();
        bool stop_idx =false;//stop when there isn't a element leq to val
        int val=0;
        while(!stop_idx){
            stop_idx= true;
            int next = val+1;
            int last = next+1;
            for(int i =0;i<rows;i++){
                for(int j =0;j<cols;j++){
                    if(matrix[i][j]==next){
                        if(!(valid(matrix,rows,cols,i+1,j,val)||valid(matrix,rows,cols,i,j+1,val)||valid(matrix,rows,cols,i-1,j,val)||valid(matrix,rows,cols,i,j-1,val))){
                            matrix[i][j]=last;
                            stop_idx= false;
                        }
                    }
                }
            }
            val++;
        }
        return matrix;
    }
};

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值