




Sponsored
Sponsored
This approach uses Depth-First Search (DFS) to mark all 'O's connected to the boundary as safe. These 'O's cannot be converted to 'X' because they are on the boundary or connected to the boundary. The rest of the 'O's can be safely converted to 'X'.
Time Complexity: O(m * n), Space Complexity: O(m * n) due to the DFS recursion stack.
1class Solution:
2    def solve(self, board: List[List[str]]) -> None:
3        def dfs(row, col):
4            if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]) or board[row][col] != 'O':
5                return
6            board[row][col] = 'A'
7            dfs(row - 1, col)
8            dfs(row + 1, col)
9            dfs(row, col - 1)
10            dfs(row, col + 1)
11
12        m, n = len(board), len(board[0])
13        if m == 0:
14            return
15
16        for i in range(m):
17            if board[i][0] == 'O':
18                dfs(i, 0)
19            if board[i][n - 1] == 'O':
20                dfs(i, n - 1)
21
22        for j in range(n):
23            if board[0][j] == 'O':
24                dfs(0, j)
25            if board[m - 1][j] == 'O':
26                dfs(m - 1, j)
27
28        for i in range(m):
29            for j in range(n):
30                if board[i][j] == 'O':
31                    board[i][j] = 'X'
32                elif board[i][j] == 'A':
33                    board[i][j] = 'O'In the Python solution, dfs marks border-connected 'O's with 'A'. After processing the board, it swaps 'O's with 'X's and 'A's with 'O's to achieve the desired output.
This approach uses Breadth-First Search (BFS) utilizing a queue to explore 'O's connected to the boundary. This approach is iterative and avoids deep recursion, keeping the method stack usage low.
Time Complexity: O(m * n), Space Complexity: O(m * n) for the queue's maximal use.
1import 
Using BFS with a queue in Java, border-connected 'O's are marked, securing them from conversion to 'X'. This iterative method handles potential issue with recursion depth.