首页 > 其他 > 详细

[LeetCode] 130. Surrounded Regions_Medium tag: DFS

时间:2018-08-08 00:15:55      阅读:219      评论:0      收藏:0      [点我收藏+]

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

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

 

[LeetCode] 130. Surrounded Regions_Medium tag: DFS

原文:https://www.cnblogs.com/Johnsonxiong/p/9440427.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!