The surrounded regions problem in Python
Problem statement
This problem is based on finding regions in our binary 2D matrix surrounded by other elements. The elements are donated by X and O. We need to replace the O with X if other elements surround them. A cell is considered to be surrounded if either of these two conditions are met:
All its surrounding cells are
X.The surrounding cells are out of the bound of the matrix.
An example of this is given below:
As we can see, the two O which are surrounded by X have been converted to X.
This problem requires an understanding of DFS. We can brush up on our knowledge here.
Solution
Let's take a look at the code for this problem:
def solve(board):rows = len(board)columns = len(board[0])for col in range(columns):dfs(board, 0, col, rows, columns)dfs(board, rows - 1, col, rows, columns)for row in range(rows):dfs(board, row, 0, rows, columns)dfs(board, row, columns - 1, rows, columns)for row in range(rows):for col in range(columns):if board[row][col] == 'O':board[row][col] = 'X'elif board[row][col] == 'V':board[row][col] = 'O'def dfs(board, row, col, rows, columns):if row < 0 or row >= rows or col < 0 or col >= columns or board[row][col] != 'O':returnboard[row][col] = 'V'dfs(board, row - 1, col, rows, columns)dfs(board, row + 1, col, rows, columns)dfs(board, row, col - 1, rows, columns)dfs(board, row, col + 1, rows, columns)
Explanation
The code is explained below:
Line 1: This is the definition of the
solvefunction, which takes the 2Dboardas a parameter.Lines 2–3: We retrieve the size of the rows and columns of the
boardmatrix.Lines 5–7: We iterate over the cells in the first and last rows of the matrix. Mark each visited cell with
OasVto indicate that it has been visited during the DFS process.Lines 9–11: Similarly, we iterate over the cells in the first and last columns of the matrix and mark each visited cell with
OasV.Lines 13–18: We iterate over every cell in the matrix. If the cell contains
O, it means it is part of a surrounding region and should be changed toX. If the cell containsV, it means it was visited during the DFS process and should be restored toObecause it is not surrounded.Lines 20–29: The
dfsfunction takes two parameters,rowandcol, representing the current cell in the matrix. It checks if the current cell is within the bounds of the matrix and if it is aOcell. If these conditions are met, it marks the current cell asVto indicate it has been visited. It then recursively calls itself on the neighboring cells (up, down, left, right) to continue the DFS process.
Free Resources