fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5.  
  6. int n, m;
  7. vector<vector<int>> grid;
  8. vector<vector<int>> vis;
  9.  
  10. int dx[] = {0, 0, 1, -1};
  11. int dy[] = {1, -1, 0, 0};
  12.  
  13. queue<pair<int,int>> q;
  14.  
  15. // DFS to mark the first island
  16. void dfs(int x, int y){
  17. vis[x][y] = 1;
  18. grid[x][y] = 2; // mark first island
  19.  
  20. q.push({x, y}); // every cell becomes a BFS source
  21.  
  22. for(int k = 0; k < 4; k++){
  23. int nx = x + dx[k];
  24. int ny = y + dy[k];
  25.  
  26. if(nx >= 0 && nx < n && ny >= 0 && ny < m &&
  27. !vis[nx][ny] && grid[nx][ny] == 1){
  28. dfs(nx, ny);
  29. }
  30. }
  31. }
  32.  
  33. int main(){
  34.  
  35. ios::sync_with_stdio(false);
  36. cin.tie(nullptr);
  37.  
  38. cin >> n >> m;
  39.  
  40. grid.assign(n, vector<int>(m));
  41. vis.assign(n, vector<int>(m, 0));
  42.  
  43. for(int i = 0; i < n; i++)
  44. for(int j = 0; j < m; j++)
  45. cin >> grid[i][j];
  46.  
  47. // Find first island
  48. bool found = false;
  49.  
  50. for(int i = 0; i < n && !found; i++){
  51. for(int j = 0; j < m && !found; j++){
  52. if(grid[i][j] == 1){
  53. dfs(i, j);
  54. found = true;
  55. }
  56. }
  57. }
  58.  
  59. vector<vector<int>> dist(n, vector<int>(m, 0));
  60.  
  61. // Multi-source BFS
  62. while(!q.empty()){
  63.  
  64. auto [x, y] = q.front();
  65. q.pop();
  66.  
  67. for(int k = 0; k < 4; k++){
  68.  
  69. int nx = x + dx[k];
  70. int ny = y + dy[k];
  71.  
  72. if(nx < 0 || nx >= n || ny < 0 || ny >= m)
  73. continue;
  74.  
  75. // Reached second island
  76. if(grid[nx][ny] == 1){
  77. cout << dist[x][y] << '\n';
  78. return 0;
  79. }
  80.  
  81. // Expand only through water
  82. if(grid[nx][ny] == 0){
  83.  
  84. grid[nx][ny] = 2; // mark visited
  85. dist[nx][ny] = dist[x][y] + 1;
  86. q.push({nx, ny});
  87. }
  88. }
  89. }
  90.  
  91. return 0;
  92. }
Success #stdin #stdout 0s 5328KB
stdin
4 4
1 0 0 0
0 0 0 0
0 0 0 0
0 0 0 1
stdout
5