-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21 May | 934. Shortest Bridge.cpp
61 lines (52 loc) · 1.69 KB
/
21 May | 934. Shortest Bridge.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
vector<vector<int>> dir = {{0,1}, {0,-1}, {1,0}, {-1, 0}};
void dfs(vector<vector<int>>& grid, int x, int y, queue<pair<int, int>>& q){
int n = grid.size();
grid[x][y] = 2;
q.push({x,y});
for(auto d : dir){
int newX = x + d[0];
int newY = y + d[1];
if(newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] == 1){
dfs(grid, newX, newY, q);
}
}
}
int shortestBridge(vector<vector<int>>& grid) {
int n = grid.size();
int firstX = -1, firstY = -1;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == 1){
firstX = i;
firstY = j;
break;
}
}
}
queue<pair<int, int>>q;
dfs(grid, firstX, firstY, q);
int dist = 0;
while(!q.empty()){
int sz = q.size();
while(sz--){
int currX = q.front().first, currY = q.front().second;
q.pop();
for(auto d: dir){
int newX = currX + d[0];
int newY = currY + d[1];
if(newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] == 1){
return dist;
}
else if(newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] == 0){
grid[newX][newY] = -1;
q.push({newX, newY});
}
}
}
dist++;
}
return dist;
}
};