Given a 2D board containing 'X'
and 'O'
(the letter O), capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
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
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O'
on the border of the board are not flipped to 'X'
. Any 'O'
that is not on the border and it is not connected to an 'O'
on the border will be flipped to 'X'
. Two cells are connected if they are adjacent cells connected horizontally or vertically.
这个题目思路实际上跟[LeetCode] 733. Flood Fill_Easy tag: BFS很像, 只不过我们将array遍历两边,第一次遍历边框, 如果是'O' 将所有相邻的'O' 都标记为visited, 然后第二次遍历
如果没有标记为visited, 将其换为'X'即可.
1. Constriants
1) None or n == 0
2) element will be only 'X' or 'O'
2. Ideas
DFS/BFS T: O(m*n) S; O(m*n)
3. Code
3.1) DFS
class Solution: def surroundRegion(self, board): if not board or len(board[0]) == 0: return lr, lc , visited = len(board), len(board[0]), set() def dfs(r, c): if 0 <= r < len(board) and 0 <= c < len(board[0]): if (r,c) not in visited and board[r][c] == 'O': visited.add((r,c)) dfs(r+1, c) dfs(r-1, c) dfs(r,c+1) dfs(r,c-1) for i in range(lr): for j in range(lc): if (i== 0 or i == lr-1 or j == 0 or j == lc -1 ) and board[i][j] == 'O' and (i,j) not in visted: dfs(i,j) for i in range(lr): for j in range(lc): if board[i][j] == 'O' and (i,j) not in visited: board[i][j] = 'X'
3.2) BFS
class Solution: def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if not board or len(board[0]) == 0 : return lr, lc, queue, visited = len(board), len(board[0]), collections.deque(), set() for i in range(lr): for j in range(lc): if (i == 0 or i == lr - 1 or j == 0 or j == lc -1) and board[i][j] == 'O' : queue.append((i,j)) visited.add((i,j)) dirs = [(0,1), (0,-1), (1,0), (-1,0)] while queue: pr, pc = queue.popleft() for c1, c2 in dirs: nr, nc = pr + c1 , pc + c2 if 0 <= nr < lr and 0 <= ncand (nr, nc) not in visited and board[nr][nc] == 'O': queue.append((nr, nc)) visited.add((nr, nc)) for i in range(lr): for j in range(lc): if board[i][j] == 'O' and (i,j) not in visited: board[i][j] = 'X'