# Easy to understand cost 219ms

• the distance of the nearest 0 from 0 to _cur
the while loop stop when _cou equal to the count of elements

class Solution {
public:

``````void bfs(int x,int y,int count,int _cou,vector<vector<int>>& matrix){
int _cur=0;
while(_cou!=count){
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
if(matrix[i][j]==_cur){
if(i+1<x&&matrix[i+1][j]>_cur+1){
matrix[i+1][j] = _cur+1;
_cou++;
}
if(j+1<y&&matrix[i][j+1]>_cur+1){
_cou++;
matrix[i][j+1] = _cur+1;
}
if(i-1>=0&&matrix[i-1][j]>_cur+1){
_cou++;
matrix[i-1][j] = _cur+1;
}
if(j-1>=0&&matrix[i][j-1]>_cur+1){
_cou++;
matrix[i][j-1] = _cur+1;
}
}
}
}
_cur++;
}
}

vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int x=matrix.size(),y = matrix[0].size();
int _cou = 0;
for(int i =0;i<x;i++){
for(int j= 0;j<y;j++){
if(matrix[i][j]==0){
_cou++;
}else{
matrix[i][j]=100;
}
}
}
bfs(x,y,x*y,_cou,matrix);
return matrix;
}
``````

};

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.