diff --git a/130 Surrounded Regions.py b/130 Surrounded Regions.py new file mode 100644 index 0000000..a9f8ef9 --- /dev/null +++ b/130 Surrounded Regions.py @@ -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