Advertisement
nikunjsoni

200

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