Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- int g[100][100];
- int r, c;
- public:
- int regionsBySlashes(vector<string>& grid) {
- // Expand the given grid.
- for(int i=0; i<grid.size(); i++)
- for(int j=0; j<grid[i].length(); j++){
- int x = i*3, y = j*3;
- if(grid[i][j] == '/')
- g[x][y+2] = g[x+1][y+1] = g[x+2][y] = 1;
- else if(grid[i][j] == '\\')
- g[x][y] = g[x+1][y+1] = g[x+2][y+2] = 1;
- }
- r = 3*grid.size();
- c = 3*grid.size();
- // Find number of connected components.
- int components = 0;
- for(int i=0; i<r; i++)
- for(int j=0; j<c; j++)
- if(!g[i][j]){
- components++;
- dfs(i, j);
- }
- return components;
- }
- void dfs(int row, int col){
- if(row<0 || row>=r || col<0 || col>=c || g[row][col] == 1) return;
- g[row][col] = 1;
- dfs(row+1, col);
- dfs(row-1, col);
- dfs(row, col+1);
- dfs(row, col-1);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement