Surrounded Regions


Problem Statement :


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: Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
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'.



Solution :



title-img


                            Solution in C :

void dfs(char** board, int rSize, int cSize, int r, int c) {
    if (r < 0 || c < 0|| r > rSize - 1 || c > cSize - 1 || board[r][c] == 'X' || board[r][c] == 'T') return;
    board[r][c] = 'T';
    dfs(board, rSize, cSize, r + 1, c);
    dfs(board, rSize, cSize, r - 1, c);
    dfs(board, rSize, cSize, r, c + 1);
    dfs(board, rSize, cSize, r, c - 1);
}

void solve(char** board, int boardSize, int* boardColSize) {
    int rSize = boardSize, cSize = boardColSize[0];
    for (int i = 0; i < cSize; i++) {
        if (board[0][i] == 'O') dfs(board, rSize, cSize, 0, i);
        if (board[rSize - 1][i] == 'O') dfs(board, rSize, cSize, rSize - 1, i);
    }
    for (int i = 0; i < rSize; i++) {
        if (board[i][0] == 'O') dfs(board, rSize, cSize, i, 0);
        if (board[i][cSize - 1] == 'O') dfs(board, rSize, cSize, i, cSize - 1);
    }
    for (int i = 0; i < rSize; i++) {
        for (int j = 0; j < cSize; j++) {
            if (board[i][j] == 'O') board[i][j] = 'X';
            if (board[i][j] == 'T') board[i][j] = 'O';
        }
    }
}
                        


                        Solution in C++ :

class Solution {
private:
    int m, n;
    
    vector<int> x = {+1, -1, 0, 0};
    vector<int> y = {0, 0, +1, -1};
    
    void dfs(int i, int j, vector<vector<char>>& board){
        if(i>=0 && i<m && j>=0 && j<n && board[i][j]=='O'){
            board[i][j] = '#';
            
            for(int k=0; k<4; k++){
                int newX = i+x[k];
                int newY = j+y[k];
                
                dfs(newX, newY, board);
            }
        }
    }
    
public:
    void solve(vector<vector<char>>& board) {
        m=board.size(), n=board[0].size();
        
        for(int i=0; i<m; i++){
            if(board[i][0] == 'O') dfs(i, 0, board);
            if(board[i][n-1] == 'O') dfs(i, n-1, board);
        }
        
        for(int j=0; j<n; j++){
            if(board[0][j] == 'O') dfs(0, j, board);
            if(board[m-1][j] == 'O') dfs(m-1, j, board);
        }
        
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(board[i][j] == '#') board[i][j] = 'O';
                else if(board[i][j] == 'O') board[i][j] = 'X';
            }
        }
    }
};
                    


                        Solution in Java :

class Solution {
    public void solve(char[][] grid) {
        for(int i=0;i<grid.length;i++){
            if(grid[i][0]!='X')dfs(grid,i,0);
            if(grid[i][grid[0].length-1]!='X')dfs(grid,i,grid[0].length-1);
        }
        for(int i=0;i<grid[0].length-1;i++){
            if(grid[0][i]!='X')dfs(grid,0,i);
            if(grid[grid.length-1][i]!='X')dfs(grid,grid.length-1,i);
        }
        swap(grid,'O','X');
        swap(grid,'p','O');
    }
    void swap(char [][]grid,char p, char q){
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(grid[i][j]==p)grid[i][j]=q;
            }
        }
    }
    void dfs(char[][]grid, int i,int j){
   if(!(i>=0 && j>=0 && i<grid.length && j<grid[0].length && grid[i][j]=='O')) return ;
        grid[i][j]='p';
        dfs(grid,i+1,j);
         dfs(grid,i-1,j);
        dfs(grid,i,j+1);
        dfs(grid,i,j-1);
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def nearme(self, return_list: List[List[int]], rownum:int,colnum:int, which:int)-> bool:
        return (return_list[rownum][colnum-1] == which or return_list[rownum][colnum+1] == which or return_list[rownum+1][colnum] == which or return_list[rownum-1][colnum] == which)
    def aroundme(self, return_list, rownum:int,colnum:int, which)-> bool:
        return (return_list[rownum][colnum-1] == which and return_list[rownum][colnum+1] == which and return_list[rownum+1][colnum] == which and return_list[rownum-1][colnum] == which)
        
    def createTag(self, board: List[List[str]]) -> List[List[int]]:
        m = len(board)
        n = len(board[0])
        rowlow = 0
        rowhigh = m - 1
        columlow = 0
        columhigh = n - 1
        return_set = set()
        for j in range(columlow,columhigh + 1):
            if board[rowlow][j] == "O":
                board[rowlow][j] = "C"
                return_set.add((rowlow,j))
            if board[rowhigh][j] == "O":
                board[rowhigh][j] = "C"
                return_set.add((rowhigh,j))
        for i in range(rowlow +1,rowhigh):
            if board[i][columlow] == "O":
                board[i][columlow] = "C"
                return_set.add((i,columlow))
            if board[i][columhigh] == "O":
                board[i][columhigh] = "C"
                return_set.add((i,columhigh))
        '''columlow += 1
        rowlow += 1
        columhigh -= 1
        rowhigh -= 1
        
        while columlow<=columhigh and rowlow<=rowhigh:
            for j in range(columlow,columhigh+1):                    
                if board[rowlow][j] == "O":
                    if self.nearme(return_list, rowlow, j, 2):
                        return_list[rowlow][j] = 2
                    elif self.aroundme(board,rowlow,j,"X"):
                        return_list[rowlow][j] = 1
                else: return_list[rowlow][j] = 0
                if board[rowhigh][j] == "O":
                    if self.nearme(return_list, rowhigh, j, 2):
                        return_list[rowhigh][j] = 2
                    elif self.aroundme(board,rowhigh,j,"X"):
                        return_list[rowhigh][j] = 1
                else: return_list[rowhigh][j] = 0
            for i in range(rowlow+1,rowhigh):
                if board[i][columlow] == "O":
                    if self.nearme(return_list, i, columlow, 2):
                        return_list[i][columlow] = 2
                    elif self.aroundme(board,i,columlow,"X"):
                        return_list[i][columlow] = 1
                else: return_list[i][columlow] = 0
                if board[i][columhigh] == "O":
                    if self.nearme(return_list, i, columhigh, 2):
                        return_list[i][columhigh] = 2
                    elif self.aroundme(board,i,columhigh,"X"):
                        return_list[i][columhigh] = 1
                else: return_list[i][columhigh] = 0
            
            for j in reversed(range(columlow,columhigh+1)):                    
                if board[rowlow][j] == "O":
                    if self.nearme(return_list, rowlow, j, 2):
                        return_list[rowlow][j] = 2
                else: return_list[rowlow][j] = 0
                if board[rowhigh][j] == "O":
                    if self.nearme(return_list, rowhigh, j, 2):
                        return_list[rowhigh][j] = 2
                else: return_list[rowhigh][j] = 0
            for i in reversed(range(rowlow+1,rowhigh)):
                if board[i][columlow] == "O":
                    if self.nearme(return_list, i, columlow, 2):
                        return_list[i][columlow] = 2
                else: return_list[i][columlow] = 0
                if board[i][columhigh] == "O":
                    if self.nearme(return_list, i, columhigh, 2):
                        return_list[i][columhigh] = 2
                else: return_list[i][columhigh] = 0

            columlow += 1
            rowlow += 1
            columhigh -= 1
            rowhigh -= 1

        columlow -= 1
        rowlow -= 1
        columhigh += 1
        rowhigh += 1

        while columlow > 0 and n > columhigh and 0 < rowlow and m > rowhigh:
            for j in range(columlow,columhigh+1):                    
                if board[rowlow][j] == "O":
                    if self.nearme(return_list, rowlow, j, 2):
                        return_list[rowlow][j] = 2
                else: return_list[rowlow][j] = 0
                if board[rowhigh][j] == "O":
                    if self.nearme(return_list, rowhigh, j, 2):
                        return_list[rowhigh][j] = 2
                else: return_list[rowhigh][j] = 0
            for i in range(rowlow+1,rowhigh):
                if board[i][columlow] == "O":
                    if self.nearme(return_list, i, columlow, 2):
                        return_list[i][columlow] = 2
                else: return_list[i][columlow] = 0
                if board[i][columhigh] == "O":
                    if self.nearme(return_list, i, columhigh, 2):
                        return_list[i][columhigh] = 2
                else: return_list[i][columhigh] = 0
            
            for j in reversed(range(columlow,columhigh+1)):                    
                if board[rowlow][j] == "O":
                    if self.nearme(return_list, rowlow, j, 2):
                        return_list[rowlow][j] = 2
                else: return_list[rowlow][j] = 0
                if board[rowhigh][j] == "O":
                    if self.nearme(return_list, rowhigh, j, 2):
                        return_list[rowhigh][j] = 2
                else: return_list[rowhigh][j] = 0
            for i in reversed(range(rowlow+1,rowhigh)):
                if board[i][columlow] == "O":
                    if self.nearme(return_list, i, columlow, 2):
                        return_list[i][columlow] = 2
                else: return_list[i][columlow] = 0
                if board[i][columhigh] == "O":
                    if self.nearme(return_list, i, columhigh, 2):
                        return_list[i][columhigh] = 2
                else: return_list[i][columhigh] = 0

            columlow -= 1
            rowlow -= 1
            columhigh += 1
            rowhigh += 1'''
        return return_set
 
    def solve(self, board: List[List[str]]) -> None:
        m = len(board)
        n = len(board[0])
        rowlow = 0
        rowhigh = m - 1
        columlow = 0
        columhigh = n - 1
        return_set = set()
        for j in range(columlow,columhigh + 1):
            if board[rowlow][j] == "O":
                board[rowlow][j] = "C"
                return_set.add((rowlow + 1,j))
            if board[rowhigh][j] == "O":
                board[rowhigh][j] = "C"
                return_set.add((rowhigh - 1,j))
        for i in range(rowlow +1,rowhigh):
            if board[i][columlow] == "O":
                board[i][columlow] = "C"
                return_set.add((i,columlow + 1))
            if board[i][columhigh] == "O":
                board[i][columhigh] = "C"
                return_set.add((i,columhigh - 1))
        while return_set != set():
            i,j = return_set.pop()
            if rowlow < i < rowhigh and columlow < j < columhigh and board[i][j] == "O":
                board[i][j] = "C"
                return_set.add((i,j+1)) 
                return_set.add((i,j-1))
                return_set.add((i-1,j))
                return_set.add((i+1,j))
        for i in range(m):
            for j in range(n):
                if board[i][j] == "C": board[i][j] = "O"
                elif board[i][j] == "O": board[i][j] = "X"
                    


View More Similar Problems

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →