|
| 1 | +""" |
| 2 | +Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. |
| 3 | +
|
| 4 | +A region is captured by flipping all 'O's into 'X's in that surrounded region. |
| 5 | +
|
| 6 | +For example, |
| 7 | +X X X X |
| 8 | +X O O X |
| 9 | +X X O X |
| 10 | +X O X X |
| 11 | +After running your function, the board should be: |
| 12 | +
|
| 13 | +X X X X |
| 14 | +X X X X |
| 15 | +X X X X |
| 16 | +X O X X |
| 17 | +""" |
| 18 | +__author__ = 'Danyang' |
| 19 | +CONNECTED = 'C' |
| 20 | +class Solution: |
| 21 | + def solve(self, board): |
| 22 | + """ |
| 23 | + Graph Theory |
| 24 | + Algorithm1: bfs, to tell whether it is on the boarder |
| 25 | + Algorithm2: bfs, to get the connectivity graph |
| 26 | + :param board: a 2D array |
| 27 | + :return: NIL, Capture all regions by modifying the input board in-place. |
| 28 | + """ |
| 29 | + if not board or not board[0]: |
| 30 | + return |
| 31 | + q = [] |
| 32 | + # scan the boarder |
| 33 | + m = len(board) |
| 34 | + n = len(board[0]) |
| 35 | + for i in xrange(m): |
| 36 | + if board[i][0]=='O': q.append((i, 0)) |
| 37 | + if board[i][n-1]=='O': q.append((i, n-1)) |
| 38 | + for j in xrange(1, n-1): |
| 39 | + if board[0][j]=='O': q.append((0, j)) |
| 40 | + if board[m-1][j]=='O': q.append((m-1, j)) |
| 41 | + |
| 42 | + i = 0 |
| 43 | + while i<len(q): # dynamically expanding, no deletion of elements |
| 44 | + cor = q[i] |
| 45 | + board[cor[0]][cor[1]]=CONNECTED |
| 46 | + try: # left |
| 47 | + if board[cor[0]][cor[1]-1]=='O': q.append((cor[0], cor[1]-1)) |
| 48 | + except IndexError: |
| 49 | + pass |
| 50 | + try: # right |
| 51 | + if board[cor[0]][cor[1]+1]=='O': q.append((cor[0], cor[1]+1)) |
| 52 | + except IndexError: |
| 53 | + pass |
| 54 | + try: # up |
| 55 | + if board[cor[0]-1][cor[1]]=='O': q.append((cor[0]-1, cor[1])) |
| 56 | + except IndexError: |
| 57 | + pass |
| 58 | + try: # down |
| 59 | + if board[cor[0]+1][cor[1]]=='O': q.append((cor[0]+1, cor[1])) |
| 60 | + except IndexError: |
| 61 | + pass |
| 62 | + |
| 63 | + i += 1 |
| 64 | + |
| 65 | + for i in xrange(m): |
| 66 | + for j in xrange(n): |
| 67 | + if board[i][j]=='O': |
| 68 | + board[i][j] = 'X' |
| 69 | + elif board[i][j]==CONNECTED: |
| 70 | + board[i][j] = 'O' |
| 71 | + |
| 72 | + |
| 73 | +if __name__=="__main__": |
| 74 | + board = [ |
| 75 | + ['X', 'X', 'X', 'X'], |
| 76 | + ['X', 'O', 'O', 'X'], |
| 77 | + ['X', 'X', 'O', 'X'], |
| 78 | + ['X', 'O', 'X', 'X'] |
| 79 | + ] |
| 80 | + expected_board = [ |
| 81 | + ['X', 'X', 'X', 'X'], |
| 82 | + ['X', 'X', 'X', 'X'], |
| 83 | + ['X', 'X', 'X', 'X'], |
| 84 | + ['X', 'O', 'X', 'X'] |
| 85 | + ] |
| 86 | + Solution().solve(board) |
| 87 | + assert board==expected_board |
| 88 | + |
| 89 | + |
| 90 | + |
| 91 | + |
0 commit comments