Advertisement
CR7CR7

replace O's with X's

Sep 4th, 2023
889
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. class Solution:
  2.     def fill(self, n, m, mat):
  3.         # Use the input matrix itself as the visited array
  4.         # Mark all 'O' cells that are on the border of the matrix with '#'
  5.         for i in range(n):
  6.             if mat[i][0] == 'O':
  7.                 mat[i][0] = '#'
  8.             if mat[i][m - 1] == 'O':
  9.                 mat[i][m - 1] = '#'
  10.         for j in range(m):
  11.             if mat[0][j] == 'O':
  12.                 mat[0][j] = '#'
  13.             if mat[n - 1][j] == 'O':
  14.                 mat[n - 1][j] = '#'
  15.  
  16.         # Use a BFS approach to mark all 'O' cells that are connected to the border cells with '#'
  17.         queue = []
  18.         for i in range(n):
  19.             for j in range(m):
  20.                 if mat[i][j] == '#':
  21.                     queue.append((i, j))
  22.  
  23.         while queue:
  24.             i, j = queue.pop(0)
  25.  
  26.             for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
  27.                 new_i = i + di
  28.                 new_j = j + dj
  29.                 if 0 <= new_i < n and 0 <= new_j < m and mat[new_i][new_j] == 'O':
  30.                     mat[new_i][new_j] = '#'
  31.                     queue.append((new_i, new_j))
  32.  
  33.         # Replace all 'O' cells that are not marked with 'X'
  34.         # Restore the marked cells back to 'O'
  35.         for i in range(n):
  36.             for j in range(m):
  37.                 if mat[i][j] == '#':
  38.                     mat[i][j] = 'O'
  39.                 else:
  40.                     mat[i][j] = 'X'
  41.  
  42.         return mat
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement