Advertisement
imashutosh51

Surrounded regions

Oct 16th, 2022 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. /*
  2. Logic:This is proper DFS problem.
  3. observation:Only that bulk of O's which is on the corner will be remained O.
  4. so we run dfs for every corner zero and change it to small o that means it will remain
  5. We are changing it into small o so that we can differentiate between which O's to be
  6. O and which to be changed.
  7. O after all operations.
  8. rest all O will be captured.
  9. */
  10.  
  11. void dfs(vector<vector<char>> &board,int i,int j,int r,int c){
  12.     int row[4]={-1,0,1,0};
  13.     int col[4]={0,1,0,-1};
  14.     board[i][j]='o';
  15.     for(int k=0;k<4;k++){
  16.          int new_i=i+row[k];
  17.          int new_j=j+col[k];
  18.          if(new_i>=0 && new_i<r && new_j>=0 && new_j<c && board[new_i][new_j]=='O') dfs(board,new_i,new_j,r,c);
  19.     }
  20. }
  21.  
  22. class Solution {
  23. public:
  24.     void solve(vector<vector<char>>& board) {
  25.         int r=board.size();
  26.         int c=board[0].size();
  27.         for(int i=0;i<r;i++){
  28.             for(int j=0;j<c;j++){
  29.                 if((i==0 || i==r-1 || j==0 || j==c-1 ) && board[i][j]=='O')dfs(board,i,j,r,c);
  30.             }
  31.         }
  32.  
  33.         for(int i=0;i<r;i++){
  34.             for(int j=0;j<c;j++){
  35.                 if(board[i][j]=='o') board[i][j]='O';
  36.                 else board[i][j]='X';
  37.             }
  38.         }
  39.     }
  40. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement