.
Last Updated:
Question Source: https://leetcode.com/problems/surrounded-regions
A region is NOT surrounded if any of the os are able to reach the edge of the map. We can use either BFS or DFS to traverse any region and see if it reaches the edge.
Main tasks:
os to xs if the region is surroundedDetailed Steps
Start at cell (0,0).
o move to next cello start BFSBFS:
oso to xfrom collections import deque
class Solution:
def solve(self, board):
"""
Do not return anything, modify board in-place instead.
"""
from collections import deque
class Solution:
def solve(self, board):
"""
Do not return anything, modify board in-place instead.
"""
rows = len(board)
cols = len(board[0]
visited = {}
def bfs(r.c):
coor = [r,c]
surrounded = True
queue = deque()
island = {}
queue.append(cell)
while queue:
dir = [(0,1),(0,-1),(1,0),(-1,0)]
for d in dir:
r = coor[0] + dir[0]
c = coor[1] + dir[1]
# edge is reached - not surrounded
if r == len(board) or c == len(board[0]):
surrounded = False
queue.popleft()
# keep looking for more 'O'
elif board[r][c] == 'O' and board[r][c] not in visited:
queue.append((r,c))
island.add((r,c))
queue.popleft()
# toggle 'O' to 'X' if surrounded
if surrounded:
for r,c in island:
board[r][c] = 'X'
for r in rows:
for c in cols:
island = {}
cell = board[r][c]
if cell not in visited and cell == 'O':
bfs(r,c)
print(board)
s = Solution()
board = [[X,X,X,X],
[X,O,O,X],
[X,X,O,X],
[X,O,X,X]]
s.solve(board)