Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:This is proper DFS problem.
- observation:Only that bulk of O's which is on the corner will be remained O.
- so we run dfs for every corner zero and change it to small o that means it will remain
- We are changing it into small o so that we can differentiate between which O's to be
- O and which to be changed.
- O after all operations.
- rest all O will be captured.
- m-2: dont check the whole matrix, check the corner rows and columns only
- */
- from typing import List
- def dfs(board, i, j, r, c):
- row = [-1, 0, 1, 0]
- col = [0, 1, 0, -1]
- board[i][j] = 'o' # mark safe
- for k in range(4):
- new_i = i + row[k]
- new_j = j + col[k]
- if (0 <= new_i < r and
- 0 <= new_j < c and
- board[new_i][new_j] == 'O'):
- dfs(board, new_i, new_j, r, c)
- class Solution:
- def solve(self, board: List[List[str]]) -> None:
- if not board:
- return
- r = len(board)
- c = len(board[0])
- # Traverse whole board and check boundary cells
- for i in range(r):
- for j in range(c):
- if (i == 0 or i == r-1 or j == 0 or j == c-1) and board[i][j] == 'O':
- dfs(board, i, j, r, c)
- # Final conversion
- for i in range(r):
- for j in range(c):
- if board[i][j] == 'o':
- board[i][j] = 'O'
- else:
- board[i][j] = 'X'
Advertisement
Add Comment
Please, Sign In to add comment