Skip to content

Instantly share code, notes, and snippets.

@alphaCoder
Created December 22, 2019 17:25
Show Gist options
  • Save alphaCoder/584f619a1a0ce5125ff77b25880a0032 to your computer and use it in GitHub Desktop.
Save alphaCoder/584f619a1a0ce5125ff77b25880a0032 to your computer and use it in GitHub Desktop.
Surrounded Regions
class Solution:
def solve(self, board: List[List[str]]) -> None:
if not board or len(board) == 0:
return
topRow, bottomRow = 0, len(board) - 1
leftBorder, rightBorder = 0, len(board[0]) - 1
def inBounds(i, j):
return i >= topRow and i <= bottomRow and j >= leftBorder and j <= rightBorder
def boundaryDfs(i, j):
if not inBounds(i, j):
return
if board[i][j] == 'O':
board[i][j] = '*'
arr =[(i-1,j), (i+1, j), (i, j-1), (i, j+1)]
for (x, y) in arr:
if inBounds(x, y) and board[x][y] == 'O':
boundaryDfs(x, y)
for n in range(len(board[0])):
if board[0][n] == 'O':
boundaryDfs(0, n)
if board[bottomRow][n] == 'O':
boundaryDfs(bottomRow, n)
for m in range(len(board)):
if board[m][0] == 'O':
boundaryDfs(m, 0)
if board[m][rightBorder] == 'O':
boundaryDfs(m, rightBorder)
for m in range(len(board)):
for n in range(len(board[0])):
if board[m][n] == 'O':
board[m][n] = 'X'
elif board[m][n] == '*':
board[m][n] = 'O'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment