Advertisement
nikunjsoni

959

Apr 24th, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. class Solution {
  2. int g[100][100];
  3. int r, c;
  4.  
  5. public:
  6.     int regionsBySlashes(vector<string>& grid) {
  7.         // Expand the given grid.
  8.         for(int i=0; i<grid.size(); i++)
  9.             for(int j=0; j<grid[i].length(); j++){
  10.                 int x = i*3, y = j*3;
  11.                 if(grid[i][j] == '/')
  12.                     g[x][y+2] = g[x+1][y+1] = g[x+2][y] = 1;
  13.                 else if(grid[i][j] == '\\')
  14.                     g[x][y] = g[x+1][y+1] = g[x+2][y+2] = 1;
  15.             }
  16.        
  17.         r = 3*grid.size();
  18.         c = 3*grid.size();
  19.         // Find number of connected components.
  20.         int components = 0;
  21.         for(int i=0; i<r; i++)
  22.             for(int j=0; j<c; j++)
  23.                 if(!g[i][j]){
  24.                     components++;
  25.                     dfs(i, j);
  26.                 }
  27.         return components;
  28.     }
  29.    
  30.     void dfs(int row, int col){
  31.         if(row<0 || row>=r || col<0 || col>=c || g[row][col] == 1) return;
  32.         g[row][col] = 1;
  33.         dfs(row+1, col);
  34.         dfs(row-1, col);
  35.         dfs(row, col+1);
  36.         dfs(row, col-1);
  37.     }
  38.    
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement