- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Surrounded Regions 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)
Example
Let us see the following implementation to get better understanding −
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ 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' 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)
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"]]