forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
surrounded-regions.py
65 lines (57 loc) · 1.68 KB
/
surrounded-regions.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from __future__ import print_function
# Time: O(m * n)
# Space: O(m + n)
#
# Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
#
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
#
# For example,
# X X X X
# X O O X
# X X O X
# X O X X
# After running your function, the board should be:
#
# X X X X
# X X X X
# X X X X
# X O X X
#
import collections
class Solution:
# @param board, a 2D array
# Capture all regions by modifying the input board in-place.
# Do not return any value.
def solve(self, board):
if not board:
return
q = collections.deque([])
for i in xrange(len(board)):
q.append((i, 0))
q.append((i, len(board[0]) - 1))
for j in xrange(len(board[0])):
q.append((0, j))
q.append((len(board) - 1, j))
while q:
i, j = q.popleft()
if board[i][j] in ['O', 'V']:
board[i][j] = 'V'
for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
if 0 <= x < len(board) and 0 <= y < len(board[0]) and \
board[x][y] == 'O':
board[x][y] = 'V'
q.append((x, y))
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if board[i][j] != 'V':
board[i][j] = 'X'
else:
board[i][j] = 'O'
if __name__ == "__main__":
board = [['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']]
Solution().solve(board)
print(board)