Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def fill(self, n, m, mat):
- # Use the input matrix itself as the visited array
- # Mark all 'O' cells that are on the border of the matrix with '#'
- for i in range(n):
- if mat[i][0] == 'O':
- mat[i][0] = '#'
- if mat[i][m - 1] == 'O':
- mat[i][m - 1] = '#'
- for j in range(m):
- if mat[0][j] == 'O':
- mat[0][j] = '#'
- if mat[n - 1][j] == 'O':
- mat[n - 1][j] = '#'
- # Use a BFS approach to mark all 'O' cells that are connected to the border cells with '#'
- queue = []
- for i in range(n):
- for j in range(m):
- if mat[i][j] == '#':
- queue.append((i, j))
- while queue:
- i, j = queue.pop(0)
- for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
- new_i = i + di
- new_j = j + dj
- if 0 <= new_i < n and 0 <= new_j < m and mat[new_i][new_j] == 'O':
- mat[new_i][new_j] = '#'
- queue.append((new_i, new_j))
- # Replace all 'O' cells that are not marked with 'X'
- # Restore the marked cells back to 'O'
- for i in range(n):
- for j in range(m):
- if mat[i][j] == '#':
- mat[i][j] = 'O'
- else:
- mat[i][j] = 'X'
- return mat
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement