|
| 1 | +class Solution: |
| 2 | + def solve(self, board: List[List[str]]) -> None: |
| 3 | + n = len(board) |
| 4 | + m = len(board[0]) |
| 5 | + |
| 6 | + # If board have less than 3 size in any direction: nothing to do, because all cells located on borders |
| 7 | + if n < 3 or m < 3: |
| 8 | + return |
| 9 | + |
| 10 | + # DFS to look for the next 'O' cell upper, lower, to the right and to the left of current coordinates |
| 11 | + # If 'O' cell is found, recursevly mark this cell as 'R' which is mean REACHED |
| 12 | + def dfs(row: int, col: int) -> None: |
| 13 | + board[row][col] = 'R' |
| 14 | + if row > 0 and board[row - 1][col] == 'O': |
| 15 | + dfs(row - 1, col) |
| 16 | + if row < n - 1 and board[row + 1][col] == 'O': |
| 17 | + dfs(row + 1, col) |
| 18 | + if col > 0 and board[row][col - 1] == 'O': |
| 19 | + dfs(row, col - 1) |
| 20 | + if col < m - 1 and board[row][col + 1] == 'O': |
| 21 | + dfs(row, col + 1) |
| 22 | + |
| 23 | + # Go and check left and right borders of the board |
| 24 | + for row in range(n): |
| 25 | + if board[row][0] == 'O': |
| 26 | + dfs(row, 0) |
| 27 | + if board[row][m - 1] == 'O': |
| 28 | + dfs(row, m - 1) |
| 29 | + |
| 30 | + # Same for check up and down borders of the board |
| 31 | + # Since corners (0,0) and (n - 1, m - 1) where checked in previous cycle, skip them in this one |
| 32 | + for col in range(1, m - 1): |
| 33 | + if board[0][col] == 'O': |
| 34 | + dfs(0, col) |
| 35 | + if board[n - 1][col] == 'O': |
| 36 | + dfs(n - 1, col) |
| 37 | + |
| 38 | + # Follow through the whole board and flip all 'R' cells back into 'O' and all 'O' cell to 'X' |
| 39 | + # since they're unreacheable from the board located 'O' cell if any |
| 40 | + for row in range(n): |
| 41 | + for col in range(m): |
| 42 | + if board[row][col] == 'O': |
| 43 | + board[row][col] = 'X' |
| 44 | + elif board[row][col] == 'R': |
| 45 | + board[row][col] = 'O' |
0 commit comments