思路: 已经告知了是两个岛屿,所以先通过DFS找到其中一个岛并且给其标记,然后把其周围的0收起来,因为跟第二个岛如果隔开的话肯定是有0的,如果没0那就只有一个岛。然后对这一层的0进行广搜,也不断的进行标记,这层0完了以后再广搜下一层,直到找到下一个为1的就是岛屿了。
1 class Solution { 2 public: 3 vector<int> direction{-1, 0, 1, 0, -1}; 4 5 int shortestBridge(vector<vector<int>>& A) { 6 int m = A.size(), n = A[0].size(); 7 queue<pair<int, int>> points; 8 //使用dfs寻找第一个岛屿,并把1变成2 9 bool flipped = false; 10 for (int i(0); i < m; ++i) { 11 if (flipped) break; 12 for (int j(0); j < n; ++j) { 13 if (A[i][j] == 1) { 14 dfs(points, A, m, n, i, j); 15 flipped = true; 16 break; 17 } 18 } 19 } 20 //bfs寻找第二个岛屿,把过程中的0变成2 21 int x, y; 22 int level = 0; 23 while (!points.empty()) { 24 ++level; 25 int n_points = points.size(); 26 while (n_points--) { 27 auto [r, c] = points.front(); 28 points.pop(); 29 for (int k(0); k < 4; ++k) { 30 x = r + direction[k], y = c + direction[k + 1]; 31 if (x >= 0 && y >= 0 && x < m && y < n) { 32 if (A[x][y] == 2) continue; 33 if (A[x][y] == 1) return level; 34 points.push({x, y}); 35 A[x][y] = 2; 36 } 37 } 38 } 39 } 40 return 0; 41 } 42 43 void dfs(queue<pair<int, int>>& points, vector<vector<int>>& grid, int m, int n, 44 int i, int j) { 45 //先考察方向问题 46 if (i < 0 || j < 0 || i == m || j == n || grid[i][j] == 2) return; 47 //再考虑别的推出方式 48 if (grid[i][j] == 0) { 49 points.push({i, j}); 50 return; 51 } 52 grid[i][j] = 2; 53 dfs(points, grid, m, n, i - 1, j); 54 dfs(points, grid, m, n, i + 1, j); 55 dfs(points, grid, m, n, i, j - 1); 56 dfs(points, grid, m, n, i, j + 1); 57 } 58 };