[leetcode] 130. Surrounded Regions @ python

本文介绍了一种使用BFS算法解决二维棋盘上O型字符被X型字符围困的问题。通过先标记边界上的O并进行搜索,再将未被触及的O转化为X,实现了对被围困区域的有效捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

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.

解法

BFS. 首先找出在边界的O, 将它们加到队列中, 然后对它们进行BFS搜索, 将它和它相邻的O转化为D. 棋盘里剩下的O则是被X包围住的O, 遍历棋盘, 将O改为X, 将D还原为O.
Time: O(n)
Space: O(n)

代码

class Solution(object):
    def solve(self, board):
        """
        :type board: List[List[str]]
        :rtype: None Do not return anything, modify board in-place instead.
        """
        if not board: return
        row, col = len(board), len(board[0])
        q = collections.deque()
        
        # get the index of all O on the boarder
        for r in range(row):
            for c in range(col):
                if r in [0, row-1] or c in [0, col-1] and board[r][c]=='O':
                    q.append((r,c))
                    
        # bfs, make the adjacent O into D
        while q:
            x, y = q.popleft()
            if 0 <= x < row and 0 <= y < col and board[x][y] == 'O':
                board[x][y] = 'D'              
                for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:                
                    q.append((x+dx, y+dy))
                    
        # make the rest of O into X and make the D into 0
        for r in range(row):
            for c in range(col):
                if board[r][c] == 'O':
                    board[r][c] = 'X'
                elif board[r][c] == 'D':
                    board[r][c] = 'O'
### 关于深度优先遍历(DFS)在 LeetCode 上的应用 #### 深度优先遍历简介 深度优先遍历是一种用于图或树结构的搜索算法,通常采用递归方式实现。它会尽可能深地探索某个分支直到无法继续为止,然后再回溯到上一层并尝试其他可能的方向[^1]。 #### 常见 LeetCode 题目及其解决方案 ##### 1. **被围绕的区域 (Surrounded Regions)** 此题要求将二维网格中所有的 'O' 替换为 'X',除非这些 'O' 连通至边界,则保持不变。可以通过 DFS 来解决该问题: ```python def solve(board): if not board or not board[0]: return m, n = len(board), len(board[0]) def dfs(x, y): if x < 0 or x >= m or y < 0 or y >= n or board[x][y] != 'O': return board[x][y] = '#' # 将与边界相连的'O'标记为'#' dfs(x - 1, y) dfs(x + 1, y) dfs(x, y - 1) dfs(x, y + 1) # 处理四条边界的'O' for i in range(m): dfs(i, 0) dfs(i, n - 1) for j in range(n): dfs(0, j) dfs(m - 1, j) # 最终替换字符 for i in range(m): for j in range(n): if board[i][j] == 'O': # 被包围的'O' board[i][j] = 'X' elif board[i][j] == '#': # 与边界连通的'O' board[i][j] = 'O' ``` 上述代码利用了 DFS 对边界上的 'O' 及与其相邻的所有 'O' 进行保护处理。 ##### 2. **二叉树的前序、中序和后序遍历** 对于二叉树的不同遍历方式,都可以借助 DFS 实现。以下是基于递归的方法来完成三种常见遍历模式的例子: - **前序遍历**:根 -> 左子树 -> 右子树 - **中序遍历**:左子树 -> 根 -> 右子树 - **后序遍历**:左子树 -> 右子树 -> 根 ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 定义通用函数模板 def preorderTraversal(root): # 或者 inorder/postorder... result = [] def traverse(node): if node is None: return result.append(node.val) # 修改此处位置可调整为不同类型的遍历 traverse(node.left) traverse(node.right) traverse(root) return result ``` 这段代码展示了如何灵活改变 `result.append` 的调用时机从而适应不同的遍历需求[^3]。 ##### 3. **字符串排列组合变换** 给定一个仅由英文字母组成的字符串 s ,返回所有可能的大写/小写字母转换后的结果列表。这也可以看作是对决策树的一种 DFS 探索过程[^5]。 ```python from typing import List def letterCasePermutation(s: str) -> List[str]: res = [] def backtrack(path, index): if index == len(s): res.append(''.join(path)) return current_char = s[index] if current_char.isalpha(): path.append(current_char.lower()) backtrack(path, index + 1) path.pop() path.append(current_char.upper()) backtrack(path, index + 1) path.pop() else: path.append(current_char) backtrack(path, index + 1) path.pop() backtrack([], 0) return res ``` 在这里,每次选择当前字符作为大写或者小写的版本加入路径,并向更深的一层递归前进;当到达叶子节点时收集整个路径形成最终答案的一部分。 --- #### 总结 以上介绍了几个典型的 LeetCode 题目以及它们对应的 DFS 解决方案。每种情况都体现了 DFS 在解决问题过程中所表现出的强大能力——无论是针对复杂数据结构还是简单的状态空间搜索都能游刃有余地应对。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值