Surrounded Regions in Python



Suppose we have a 2D board containing X and O. Capture all regions surrounded by X. A region is captured by changing all Os into Xs in that surrounded region.

X X X X
X O O X
X X O X
X O X X

After running the output will be

X X X X
X X X X
X X X X
X O X X

To solve this, we will follow these steps −

  • If board is not present, then return blank board
  • for i in range 0 to number of rows – 1 −
    • if board[i, 0] = ‘O’, then make_one(board, i, 0)
    • if board[i, length of row - 1] = ‘O’, then make_one(board, i, length of row – 1)
  • for i in range 0 to number of cols – 1 −
    • if board[0, i] = ‘O’, then make_one(board, 0, i)
    • if board[count of row – 1, i] = ‘O’, then make_one(board, count of row – 1, i)
  • for i in range 0 to number of rows
    • for j in range 0 to number of cols
      • if board[i, j] = ‘O’, then board[i, j] = ‘X’, otherwise for 1, board[i, j] = ‘O’
  • The make_one will be like −
  • if i < 0 or j < 0 or i >= row count or j >= col count or board[i, j] = ‘X’ or board[i, j] = ‘1’, then return
  • board[i, j] := 1
  • call make_one(voard, i + 1, j), make_one(voard, i - 1, j), make_one(voard, i, j + 1), make_one(voard, i, j - 1)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def solve(self, board):
      if not board:
         return board
      for i in range(len(board)):
         if board[i][0]=='O':
            self.make_one(board,i,0)
         if board[i][len(board[0])-1] == 'O':
            self.make_one(board,i,len(board[0])-1)
      for i in range(len(board[0])):
         if board[0][i]=='O':
            self.make_one(board,0,i)
         if board[len(board)-1][i] == 'O':
            self.make_one(board,len(board)-1,i)
      for i in range(len(board)):
         for j in range(len(board[i])):
            if board[i][j]=='O':
               board[i][j]='X'
            elif board[i][j]=='1':
               board[i][j]='O'
      return board
   def make_one(self, board,i,j):
      if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board[i][j]=='X' or board[i]   [j]=='1':
         return
      board[i][j]='1'
      self.make_one(board,i+1,j)
      self.make_one(board,i-1,j)
      self.make_one(board,i,j+1)
      self.make_one(board,i,j-1)
ob1 = Solution()
print(ob1.solve([["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]))

Input

[["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']]
Updated on: 2020-05-04T06:35:05+05:30

293 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements