MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / Solution

Class Solution

C++/Shortest-Bridge.cpp:5–93  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3// Space Complexity : O(V)
4
5class Solution {
6public:
7 vector<int> del_i = {1, 0, -1, 0};
8 vector<int> del_j = {0, 1, 0, -1};
9
10 bool checkWithinBounds(int i, int j, int row, int col) {
11 if (i < 0 || j < 0 || i >= row || j >= col) return false;
12 return true;
13 }
14
15 void markIsland(vector<vector<int>>& A, int i, int j) {
16 A[i][j] = -1;
17
18 for (int k = 0; k < 4; ++k)
19 {
20 int next_i = i + del_i[k];
21 int next_j = j + del_j[k];
22
23 if (checkWithinBounds(next_i, next_j, A.size(), A[0].size()) && A[next_i][next_j] == 1)
24 markIsland(A, next_i, next_j);
25 }
26
27 }
28
29 int shortestBridge(vector<vector<int>>& A) {
30 int r = A.size();
31 int c = A[0].size();
32
33 // mark island of one group as -1
34 int flag = 0;
35 for (int i = 0; i < r; ++i)
36 {
37 for (int j = 0; j < c; ++j)
38 {
39 if (A[i][j] == 1) {
40 flag = 1;
41 markIsland(A, i, j);
42 break;
43 }
44 }
45
46 if (flag) break;
47 }
48
49 // queue that represent flips on a particular path
50 queue<pair<int, int>> q;
51
52 for (int i = 0; i < r; ++i)
53 {
54 for (int j = 0; j < c; ++j)
55 {
56 if (A[i][j] == -1) {
57 q.push({i * r + j, 0});
58 }
59 }
60 }
61
62 while (!q.empty()) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected