130. 被围绕的区域

https://leetcode-cn.com/problems/surrounded-regions/comments/
两次遍历。第一次先遍历边界,dfs将所有与边界O相连的O置为‘-’。之后再遍历所有,将所有O变为X,所有’-‘变为O

class Solution:
    def solve(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        n = len(board)
        if n == 0:
            return
        m = len(board[0])
        #对四条边界上的元素dfs遍历
        for i in range(n):            
            self.dfs(i, 0, n, m, board)
            self.dfs(i, m-1, n, m, board)
        for j in range(m):
            self.dfs(0, j, n, m, board)
            self.dfs(n-1, j, n, m, board)
        #遍历所有
        for i in range(n):
            for j in range(m):
            	#注意先后顺序不能颠倒
                if board[i][j] == 'O':
                    board[i][j] = 'X'
                if board[i][j] == '-':
                    board[i][j] = 'O'
        
    def dfs(self, row, col, rows, cols, board):
        if row >= 0 and row < rows and col >= 0 and col < cols and board[row][col] == 'O':
            board[row][col] = '-'  #特殊标记
            #dfs遍历上下左右
            self.dfs(row, col-1, rows, cols, board)
            self.dfs(row, col+1, rows, cols, board)
            self.dfs(row-1, col, rows, cols, board)
            self.dfs(row+1, col, rows, cols, board)               

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值