130. Surrounded Regions | LeetCode Solution

 130. Surrounded Regions | LeetCode Solution

Given an m x n matrix board containing 'X' and 'O'capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

 

Example 1:

Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

Example 2:

Input: board = [["X"]]
Output: [["X"]]

 

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'.
class Solution {
public:
    void check(vector<vector<char>>&v , int i,int j){
        
        if(i>=0 && i<v.size() && j>=0 && j<v[0].size() && v[i][j]=='O'){
            v[i][j]='*';
         
            int dx[4]={0,0,-1,1};
            int dy[4]={-1,1,0,0};
            for(int k=0; k<4; k++){
                check(v,i+dx[k],j+dy[k]);
            }
        }
        
        
    }
    
    
    void solve(vector<vector<char>>& board) {
        
        for(int i=0; i<board[0].size(); i++){
            if(board[0][i]=='O')check(board,0,i);
        }
        for(int i=0; i<board[0].size(); i++){
            if(board[board.size()-1][i]=='O')check(board,board.size()-1,i);
        }
        for(int i=0; i<board.size(); i++){
            if(board[i][0]=='O')check(board,i,0);
        }
        for(int i=0; i<board.size(); i++){
            if(board[i][board[0].size()-1]=='O')check(board,i,board[0].size()-1);
        }
        
        for(int i=0; i<board.size(); i++){
            for(int j=0; j<board[0].size(); j++){
                if(board[i][j]=='*')board[i][j]='O';
                    else board[i][j]='X';
            }
        }
        
        
    }
};

Post a Comment

0 Comments