[LeetCode] Shortest Bridge

934. Shortest Bridge

You are given an n x n binary matrix grid where 1 represents land and 0 represents water.

An island is a 4-directionally connected group of 1’s not connected to any other 1’s. There are exactly two islands in grid.

You may change 0’s to 1’s to connect the two islands to form one island.

Return the smallest number of 0’s you must flip to connect the two islands.

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
class Solution {
queue<pair<int,int>> q;
int dx[4]{0,1,0,-1}, dy[4]{-1,0,1,0};
void bfs(vector<vector<int>>& grid, int sy, int sx) {
queue<pair<int,int>> Q;
Q.push({sy,sx});
q.push({sy,sx});
int n = grid.size(), m = grid[0].size();
grid[sy][sx] = 2;
while(!Q.empty()) {
auto [y, x] = Q.front(); Q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and grid[ny][nx] == 1) {
grid[ny][nx] = 2;
q.push({ny,nx});
Q.push({ny,nx});
}
}
}
}
void init(vector<vector<int>>& g) {
int n = g.size(), m = g[0].size();
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(g[i][j]) {
bfs(g,i,j);
return;
}
}
public:
int shortestBridge(vector<vector<int>>& grid) {
init(grid);
int res = 0;
int n = grid.size(), m = grid[0].size();
while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto [y,x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m) {
if(grid[ny][nx] == 1) return res;
if(grid[ny][nx] == 0) {
grid[ny][nx] = 2;
q.push({ny,nx});
}
}
}
}
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/26/PS/LeetCode/shortest-bridge/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.