Skip to content

Commit abdb6db

Browse files
committed
Runtime: 52 ms (Top 93.64%) | Memory: 30.70 MB (Top 71.83%)
1 parent 1f6b101 commit abdb6db

File tree

1 file changed

+24
-35
lines changed

1 file changed

+24
-35
lines changed
+24-35
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,38 @@
1-
// Runtime: 192 ms (Top 16.37%) | Memory: 30 MB (Top 73.15%)
1+
// Runtime: 52 ms (Top 93.64%) | Memory: 30.70 MB (Top 71.83%)
22

33
class Solution {
4-
bool isValid(vector<vector<int>>& grid,int r,int c,int nr,int nc,int m,int n){
5-
if(nr>=0 && nc>=0 && nr<m && nc<n && grid[nr][nc]==-1){
6-
if(grid[r][c]==0)
7-
grid[nr][nc]=1;
8-
else
9-
grid[nr][nc]=grid[r][c]+1;
10-
return 1;
11-
}
12-
return 0;
13-
}
144
public:
155
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
16-
queue<pair<int,int>> q;
17-
int m = mat.size();
18-
int n = mat[0].size();
19-
for(int i=0;i<m;i++){
20-
for(int j=0;j<n;j++){
6+
queue<pair<int,int>>q;
7+
for(int i=0;i<mat.size();i++){
8+
for(int j=0;j<mat[0].size();j++){
219
if(mat[i][j]==0)
2210
q.push({i,j});
2311
else
2412
mat[i][j]=-1;
2513
}
2614
}
15+
int length=0;
16+
int dirx[]={1,-1,0,0};
17+
int diry[]={0,0,1,-1};
2718
while(!q.empty()){
28-
auto per = q.front();
29-
int r = per.first;
30-
int c = per.second;
31-
// if()
32-
q.pop();
33-
if(isValid(mat,r,c,r-1,c,m,n)){
34-
q.push({r-1,c});
35-
}
36-
if(isValid(mat,r,c,r+1,c,m,n)){
37-
q.push({r+1,c});
38-
}
39-
if(isValid(mat,r,c,r,c-1,m,n)){
40-
q.push({r,c-1});
41-
}
42-
if(isValid(mat,r,c,r,c+1,m,n)){
43-
q.push({r,c+1});
44-
}
45-
19+
int size=q.size();
20+
length++;
21+
while(size--){
22+
auto f=q.front();
23+
q.pop();
24+
int s=f.first;
25+
int end=f.second;
26+
for(int i=0;i<4;i++){
27+
int r=s+dirx[i];
28+
int c=end+diry[i];
29+
if(r<0 || c<0 || r==mat.size() || c==mat[0].size() || mat[r][c]!=-1)
30+
continue;
31+
mat[r][c]=length;
32+
q.push({r,c});
33+
}
34+
}
4635
}
4736
return mat;
4837
}
49-
};
38+
};

0 commit comments

Comments
 (0)