-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path542. 01 Matrix.cpp
46 lines (44 loc) · 1.18 KB
/
542. 01 Matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//https://leetcode.com/problems/01-matrix/
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int r=mat.size();
int c=mat[0].size();
queue<pair<int,int>> q;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(mat[i][j]==0)
{
q.push({i,j});
}
else if(mat[i][j]==1) mat[i][j]=-1;
}
}
while(!q.empty())
{
int x=q.front().first;
int y=q.front().second;
q.pop();
if(x-1>=0 and mat[x-1][y]==-1)
{
mat[x-1][y]=1+mat[x][y];
q.push({x-1,y});
}
if(x+1<r and mat[x+1][y]==-1)
{
mat[x+1][y]=1+mat[x][y];
q.push({x+1,y});
}
if(y-1>=0 and mat[x][y-1]==-1)
{
mat[x][y-1]=1+mat[x][y];
q.push({x,y-1});
}
if(y+1<c and mat[x][y+1]==-1)
{
mat[x][y+1]=1+mat[x][y];
q.push({x,y+1});
}
}
return mat;
}