-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01_Matrix.java
57 lines (57 loc) · 1.3 KB
/
01_Matrix.java
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
47
48
49
50
51
52
53
54
55
56
57
class Trip
{
int x;
int y;
int d;
Trip(int x,int y,int d)
{
this.x=x;
this.y=y;
this.d=d;
}
}
class Solution {
public int[][] updateMatrix(int[][] mat) {
int n=mat.length;
int m=mat[0].length;
int ans[][]=new int[n][m];
int vis[][]=new int[n][m];
Queue<Trip> q=new LinkedList<Trip>();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mat[i][j]==0)
{
q.add(new Trip(i,j,0));
vis[i][j]=1;
}
else
{
vis[i][j]=0;
}
}
}
int rows[]={-1,0,1,0};
int cols[]={0,1,0,-1};
while (!q.isEmpty())
{
int r=q.peek().x;
int c=q.peek().y;
int dis=q.peek().d;
ans[r][c]=dis;
q.remove();
for(int i=0;i<4;i++)
{
int nr=r+rows[i];
int nc=c+cols[i];
while(nr<n && nr >=0 && nc<m && nc>=0 && vis[nr][nc]==0)
{
vis[nr][nc]=1;
q.add(new Trip(nr,nc,dis+1));
}
}
}
return ans;
}
}