Advertisement
nikunjsoni

1254

Apr 25th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. class Solution {
  2. int row, col;
  3. public:
  4.     int closedIsland(vector<vector<int>>& grid) {
  5.         row = grid.size();
  6.         col = grid[0].size();
  7.         for(int i=0; i<row; i++)
  8.             for(int j=0; j<col; j++)
  9.                 if((i*j == 0 || i == row-1 || j == col-1) && grid[i][j] == 0)
  10.                     dfs(i, j, grid);
  11.         int components = 0;
  12.         for(int i=0; i<row; i++)
  13.             for(int j=0; j<col; j++)
  14.                 if(grid[i][j] == 0)
  15.                     components++, dfs(i, j, grid);
  16.         return components;
  17.     }
  18.    
  19.     void dfs(int r, int c, vector<vector<int>> &grid){
  20.         if(r<0 || r >= row || c<0 || c>=col || grid[r][c] == 1) return;
  21.         grid[r][c] = 1;
  22.         dfs(r+1, c, grid);
  23.         dfs(r-1, c, grid);
  24.         dfs(r, c+1, grid);
  25.         dfs(r, c-1, grid);
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement