-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurroundedRegions.py
More file actions
38 lines (33 loc) · 1.12 KB
/
surroundedRegions.py
File metadata and controls
38 lines (33 loc) · 1.12 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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/surrounded-regions/
# Author: Miao Zhang
# Date: 2021-01-20
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board:
return []
m = len(board)
n = len(board[0])
for i in range(m):
for j in range(n):
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
if board[i][j] == 'O':
self.dfs(board, i, j)
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '#':
board[i][j] = 'O'
def dfs(self, board, i, j):
board[i][j] = '#'
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for dx, dy in dirs:
x = i + dx
y = j + dy
if 0 <= x < len(board) and 0 <= y < len(board[0]) and board[x][y] == 'O':
self.dfs(board, x, y)