imashutosh51

Surrounded regions

Oct 16th, 2022 (edited)
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. /*
  2. Logic:This is proper DFS problem.
  3. observation:Only that bulk of O's which is on the corner will be remained O.
  4. so we run dfs for every corner zero and change it to small o that means it will remain
  5. We are changing it into small o so that we can differentiate between which O's to be
  6. O and which to be changed.
  7. O after all operations.
  8. rest all O will be captured.
  9.  
  10. m-2: dont check the whole matrix, check the corner rows and columns only
  11. */
  12.  
  13. from typing import List
  14. def dfs(board, i, j, r, c):
  15.     row = [-1, 0, 1, 0]
  16.     col = [0, 1, 0, -1]
  17.    
  18.     board[i][j] = 'o'   # mark safe
  19.    
  20.     for k in range(4):
  21.         new_i = i + row[k]
  22.         new_j = j + col[k]
  23.        
  24.         if (0 <= new_i < r and
  25.             0 <= new_j < c and
  26.             board[new_i][new_j] == 'O'):
  27.            
  28.             dfs(board, new_i, new_j, r, c)
  29.  
  30.  
  31. class Solution:
  32.     def solve(self, board: List[List[str]]) -> None:
  33.         if not board:
  34.             return
  35.        
  36.         r = len(board)
  37.         c = len(board[0])
  38.        
  39.         # Traverse whole board and check boundary cells
  40.         for i in range(r):
  41.             for j in range(c):
  42.                 if (i == 0 or i == r-1 or j == 0 or j == c-1) and board[i][j] == 'O':
  43.                     dfs(board, i, j, r, c)
  44.        
  45.         # Final conversion
  46.         for i in range(r):
  47.             for j in range(c):
  48.                 if board[i][j] == 'o':
  49.                     board[i][j] = 'O'
  50.                 else:
  51.                     board[i][j] = 'X'
Advertisement
Add Comment
Please, Sign In to add comment