Skip to content

Commit

Permalink
130
Browse files Browse the repository at this point in the history
  • Loading branch information
idf committed Sep 30, 2014
1 parent 5e33086 commit d09411f
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 2 deletions.
91 changes: 91 additions & 0 deletions 130 Surrounded Regions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""
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
"""
__author__ = 'Danyang'
CONNECTED = 'C'
class Solution:
def solve(self, board):
"""
Graph Theory
Algorithm1: bfs, to tell whether it is on the boarder
Algorithm2: bfs, to get the connectivity graph
:param board: a 2D array
:return: NIL, Capture all regions by modifying the input board in-place.
"""
if not board or not board[0]:
return
q = []
# scan the boarder
m = len(board)
n = len(board[0])
for i in xrange(m):
if board[i][0]=='O': q.append((i, 0))
if board[i][n-1]=='O': q.append((i, n-1))
for j in xrange(1, n-1):
if board[0][j]=='O': q.append((0, j))
if board[m-1][j]=='O': q.append((m-1, j))

i = 0
while i<len(q): # dynamically expanding, no deletion of elements
cor = q[i]
board[cor[0]][cor[1]]=CONNECTED
try: # left
if board[cor[0]][cor[1]-1]=='O': q.append((cor[0], cor[1]-1))
except IndexError:
pass
try: # right
if board[cor[0]][cor[1]+1]=='O': q.append((cor[0], cor[1]+1))
except IndexError:
pass
try: # up
if board[cor[0]-1][cor[1]]=='O': q.append((cor[0]-1, cor[1]))
except IndexError:
pass
try: # down
if board[cor[0]+1][cor[1]]=='O': q.append((cor[0]+1, cor[1]))
except IndexError:
pass

i += 1

for i in xrange(m):
for j in xrange(n):
if board[i][j]=='O':
board[i][j] = 'X'
elif board[i][j]==CONNECTED:
board[i][j] = 'O'


if __name__=="__main__":
board = [
['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']
]
expected_board = [
['X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X'],
['X', 'O', 'X', 'X']
]
Solution().solve(board)
assert board==expected_board




4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ Welcome to raise an issue [here](https://github.com/zhangdanyangg/LeetCode/issue
### Notes
Failed attempts are kept in the source code, which are annotated as TLE (Time Limit Exceeds) or MLE (Memory Limit Exceeds).

### TODO
Question burn-down rate: 151/152 completed
### Completion
Questions: 152/152 completed

###Miscellaneous
Practice
Expand Down

0 comments on commit d09411f

Please sign in to comment.