-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathshortest_bridge.cpp
More file actions
78 lines (71 loc) · 1.78 KB
/
shortest_bridge.cpp
File metadata and controls
78 lines (71 loc) · 1.78 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Most asked question of Coding round based on Flood Fill algorithm
// Here grid is a sqaure matrix
#include <bits/stdc++.h>
using namespace std;
#define fatafat ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);
template<class T>
int dist(T a, T b)
{
return abs(a.first - b.first) + abs(a.second - b.second) - 1;
}
void flood_fill(set<pair<int, int>>&A, vector<vector<int>>&grid, int x, int y)
{
int n = grid.size();
if(x < 0 || x >= n || y < 0 || y >= n)
{
return;
}
else if (grid[x][y] != 1)
{
return;
}
A.insert({x, y});
grid[x][y] = 2; // Already visited
flood_fill(A, grid, x-1, y); // TOP
flood_fill(A, grid, x, y+1); // Right
flood_fill(A, grid, x+1, y); // Bottom
flood_fill(A, grid, x, y-1); // Right
}
int shortestBridge(vector<vector<int>>grid)
{
int n = grid.size();
set<pair<int, int>>A; // To hold all the coordinates of the island A
set<pair<int, int>>B;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (grid[i][j] == 0)
{
continue;
}
if (A.empty())
{
flood_fill(A, grid, i, j);
}
else if (B.empty() && !A.count({i,j})) // We are checking the B set is empty and the coordinates of island B are not contained in Set A.
{
flood_fill(B, grid, i, j);
}
}
}
int ans = 2 * n;
for(auto i : A)
{
for(auto j : B)
{
ans = min(ans, dist(i, j));
}
}
return ans;
}
int main()
{
fatafat
int t = 1;
// cin >>t;
while(t--)
{
}
return 0;
}