130. Surrounded Regions

130. Surrounded Regions

Medium

48951230Add to ListShare

Given an m x n matrix board containing 'X' and 'O'capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Example 1:

Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: Surrounded regions should not 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.

Example 2:

Input: board = [["X"]]
Output: [["X"]]

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'.

解法一:

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.

        board = [["X", "X", "X", "X"],
             ["X", "O", "O", "X"],
             ["X", "X", "O", "X"],
             ["X", "O", "X", "X"]]
        Solution().solve(board)

        board = [["X"]]
        Solution().solve(board)

        board = [["O", "X", "O", "O", "O", "O", "O", "O", "O"],
             ["O", "O", "O", "X", "O", "O", "O", "O", "X"],
             ["O", "X", "O", "X", "O", "O", "O", "O", "X"],
             ["O", "O", "O", "O", "X", "O", "O", "O", "O"],
             ["X", "O", "O", "O", "O", "O", "O", "O", "X"],
             ["X", "X", "O", "O", "X", "O", "X", "O", "X"],
             ["O", "O", "O", "X", "O", "O", "O", "O", "O"],
             ["O", "O", "O", "X", "O", "O", "O", "O", "O"],
             ["O", "O", "O", "O", "O", "X", "X", "O", "O"]]
        Solution().solve(board)

        解题思路:connect[][] 标记坐标联通性 
        遍历矩阵,找到“O”时且connect[x][y]未联通,则从当前位置开始广度优先搜索,
        bfs记录沿途的的所有“O”坐标点,并暂时标记为“X”。
        若周围存在边界点或者前面被标记connect联通的坐标,直接失败,并对
        中途暂时标记为X的点还原成O,并标记为联通

        时间复杂度:O(n*m) 空间复杂度:O(n*m)
        """

        # 广度优先染色
        def bfs(x: int, y: int):
            allPoints = [[x, y]]
            points = [[x, y]]
            board[x][y] = "X"

            # 把所有联通的“O”标记
            fail = False
            while not fail and len(points) > 0:
                [x0, y0] = points.pop(0)
                for d in direction:
                    x1 = x0 + d[0]
                    y1 = y0 + d[1]
                    if x1 < 0 or x1 >= n or y1 < 0 or y1 >= m or connect[x1][y1]:
                        # 到达边界流通了,或者和别人联通了
                        fail = True
                        break
                    if board[x1][y1] == "O":
                        # 暂时染色
                        board[x1][y1] = "X"
                        points.append([x1, y1])
                        allPoints.append([x1, y1])

            if fail:
                for p in allPoints:
                    board[p[0]][p[1]] = "O"
                    connect[p[0]][p[1]] = True

        n, m = len(board), len(board[0])
        # 标记联通的坐标
        connect = [[False for j in range(m)] for i in range(n)]
        direction = [[-1, 0], [0, -1], [1, 0], [0, 1]]

        for i in range(n):
            for j in range(m):
                if not connect[i][j] and board[i][j] == "O":
                    bfs(i, j)

解法二:时间和空间优化

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.

        board = [["X", "X", "X", "X"],
             ["X", "O", "O", "X"],
             ["X", "X", "O", "X"],
             ["X", "O", "X", "X"]]
        Solution().solve(board)

        board = [["X"]]
        Solution().solve(board)

        board = [["O", "X", "O", "O", "O", "O", "O", "O", "O"],
             ["O", "O", "O", "X", "O", "O", "O", "O", "X"],
             ["O", "X", "O", "X", "O", "O", "O", "O", "X"],
             ["O", "O", "O", "O", "X", "O", "O", "O", "O"],
             ["X", "O", "O", "O", "O", "O", "O", "O", "X"],
             ["X", "X", "O", "O", "X", "O", "X", "O", "X"],
             ["O", "O", "O", "X", "O", "O", "O", "O", "O"],
             ["O", "O", "O", "X", "O", "O", "O", "O", "O"],
             ["O", "O", "O", "O", "O", "X", "X", "O", "O"]]
        Solution().solve(board)

        解题思路:从四周对“O”周围进行bfs染色为“.", 最后遍历矩阵将“.”设置成“O”,“O”设置成“X”

        时间复杂度:O(n*m) 空间复杂度:O(1)
        """

        # 广度优先染色
        def bfs(x: int, y: int):
            points = [[x, y]]
            board[x][y] = "."

            # 把所有联通的“O”标记
            while len(points) > 0:
                [x0, y0] = points.pop()
                for d in direction:
                    x1 = x0 + d[0]
                    y1 = y0 + d[1]
                    if x1 < 0 or x1 >= n or y1 < 0 or y1 >= m:
                        # 边界
                        continue
                    if board[x1][y1] == "O":
                        # 染色
                        board[x1][y1] = "."
                        points.append([x1, y1])

        n, m = len(board), len(board[0])
        direction = [[-1, 0], [0, -1], [1, 0], [0, 1]]

        for i in range(n):
            if board[i][0] == "O":
                bfs(i, 0)
            if board[i][m - 1] == "O":
                bfs(i, m - 1)
        for j in range(m):
            if board[0][j] == "O":
                bfs(0, j)
            if board[n - 1][j] == "O":
                bfs(n - 1, j)

        for i in range(n):
            for j in range(m):
                if board[i][j] == "O":
                    board[i][j] = "X"
                elif board[i][j] == ".":
                    board[i][j] = "O"

 

### LeetCode Top 100 Popular Problems LeetCode provides an extensive collection of algorithmic challenges designed to help developers prepare for technical interviews and enhance their problem-solving skills. The platform categorizes these problems based on popularity, difficulty level, and frequency asked during tech interviews. The following list represents a curated selection of the most frequently practiced 100 problems from LeetCode: #### Array & String Manipulation 1. Two Sum[^2] 2. Add Two Numbers (Linked List)[^2] 3. Longest Substring Without Repeating Characters #### Dynamic Programming 4. Climbing Stairs 5. Coin Change 6. House Robber #### Depth-First Search (DFS) / Breadth-First Search (BFS) 7. Binary Tree Level Order Traversal[^3] 8. Surrounded Regions 9. Number of Islands #### Backtracking 10. Combination Sum 11. Subsets 12. Permutations #### Greedy Algorithms 13. Jump Game 14. Gas Station 15. Task Scheduler #### Sliding Window Technique 16. Minimum Size Subarray Sum 17. Longest Repeating Character Replacement #### Bit Manipulation 18. Single Number[^1] 19. Maximum Product of Word Lengths 20. Reverse Bits This list continues up until reaching approximately 100 items covering various categories including but not limited to Trees, Graphs, Sorting, Searching, Math, Design Patterns, etc.. Each category contains multiple representative questions that cover fundamental concepts as well as advanced techniques required by leading technology companies when conducting software engineering candidate assessments. For those interested in improving logical thinking through gaming activities outside traditional study methods, certain types of video games have been shown beneficial effects similar to engaging directly within competitive coding platforms [^4]. --related questions-- 1. How does participating in online coding competitions benefit personal development? 2. What specific advantages do DFS/BFS algorithms offer compared to other traversal strategies? 3. Can you provide examples illustrating how bit manipulation improves performance efficiency? 4. In what ways might regular participation in programming contests influence job interview success rates? 5. Are there any notable differences between solving problems on paper versus implementing solutions programmatically?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值