Problem Statement

Given an m x n matrix board containing 'X' and 'O'capture all regions 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"]]

Problem Link

Surrounded Regions - LeetCode

Reference Link

Given a matrix of 'O' and 'X', replace 'O' with 'X' if surrounded by 'X' - GeeksforGeeks

Reference Video

https://www.youtube.com/watch?v=0ZJViJEdtEc&ab_channel=TECHDOSE

Code (Using DFS)

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        
        int m = board.size();
        int n = board[0].size();
        
        // Step 1: Converting all O's to -'s
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(board[i][j]=='O')
                {
                    board[i][j] = '-';
                    
                }
            }
        }
        
        // Step 2: Converting -'s to O's which are connected to boundary -'s
        
        
        for(int i=0;i<m;i++)
        {
            if(board[i][0]=='-')
                dfs(i,0,m,n,board);
        }
        
        for(int i=0;i<m;i++)
        {
            if(board[i][n-1]=='-')
                dfs(i,n-1,m,n,board);
        }
        
        for(int j=0;j<n;j++)
        {
            if(board[0][j]=='-')
                dfs(0,j,m,n,board);
        }
        
        for(int j=0;j<n;j++)
        {
            if(board[m-1][j]=='-')
                dfs(m-1,j,m,n,board);
        }
        
        // Step 3: Converting remaining -'s to 'X's
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(board[i][j]=='-')
                {
                    board[i][j] = 'X';
                    
                }
            }
        }
    }
    void dfs(int i,int j,int m,int n,vector<vector<char>>& board )
    {
        
        if(i<0 || j<0 || i>m-1 || j>n-1)
            return;
        
        if(board[i][j]!='-')
            return;
        
        board[i][j] = 'O';
        
        dfs(i+1,j,m,n,board);
        dfs(i,j+1,m,n,board);
        dfs(i-1,j,m,n,board);
        dfs(i,j-1,m,n,board);
        
        
        
        
    }
};