-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSurroundedRegions.py
More file actions
41 lines (36 loc) · 1.45 KB
/
SurroundedRegions.py
File metadata and controls
41 lines (36 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Question Link - https://leetcode.com/problems/surrounded-regions/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# Find the rows and cols of the Matrix
ROWS , COLS = len(board) , len(board[0])
# DFS , function for the capture 'O' -> 'T'
def capture(r , c):
# Base case to return
if (r < 0 or c < 0 or r == ROWS or c == COLS or
board[r][c] != 'O'):
return
board[r][c] = 'T'
# Search for 4 directions
capture(r + 1, c)
capture(r - 1, c)
capture(r ,c + 1)
capture(r ,c - 1)
# 1st pahse , convert the boundary 0 to T
for r in range(ROWS):
for c in range(COLS):
if (board[r][c] == 'O' and
(r in [0 , ROWS - 1] or c in [0 , COLS - 1])):
capture(r , c)
# 2nd phase , convert the 0 to X as its not in boundary
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == 'O':
board[r][c] = 'X'
# 3rd phase , convert the T to O ,as original position
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == 'T':
board[r][c] = 'O'