天天看點

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

給定一個由0和1組成的矩陣,找到每個單元和最近的0的距離。

兩個相鄰單元的距離是1。

leetcode-542. 01 Matrix題目代碼 

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;
    }
};