You are given an m x n matrix board containing letters 'X' and 'O', capture regions that are surrounded:
- Connect: A cell is connected to adjacent cells horizontally or vertically.
- Region: To form a region connect every
'O'cell. - Surround: The region is surrounded with
'X'cells if you can connect the region with'X'cells and none of the region cells are on the edge of theboard.
To capture a surrounded region, replace all 'O's with 'X's in-place within the original board. You do not need to return anything.
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:
In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.
Example 2:
Input: board = [["X"]]
Output: [["X"]]
Constraints:
m == board.lengthn == board[i].length1 <= m, n <= 200board[i][j]is'X'or'O'.
My Solution:
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m, n = len(board), len(board[0]) def mark_connected(i, j): if j - 1 >= 0 and board[i][j - 1] == 'O': board[i][j - 1] = 'Y' mark_connected(i, j - 1) if j + 1 < n and board[i][j + 1] == 'O': board[i][j + 1] = 'Y' mark_connected(i, j + 1) if i - 1 >= 0 and board[i - 1][j] == 'O': board[i - 1][j] = 'Y' mark_connected(i - 1, j) if i + 1 < m and board[i + 1][j] == 'O': board[i + 1][j] = 'Y' mark_connected(i + 1, j) for i in [0, m - 1]: for j in range(n): if board[i][j] == 'O': # Mark the cell as not surrounded board[i][j] = 'Y' mark_connected(i, j) for j in [0, n - 1]: for i in range(1, m - 1): if board[i][j] == 'O': # Mark the cell as not surrounded board[i][j] = 'Y' mark_connected(i, j) for i in range(m): for j in range(n): if board[i][j] == 'O': board[i][j] = 'X' elif board[i][j] == 'Y': board[i][j] = 'O'


浙公网安备 33010602011771号