DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Surrounded Regions

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Example 1:

Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

Example 2:

Input: board = [["X"]]
Output: [["X"]]


  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'.


class Solution:
    def DFS(self, board, v, i, j, m, n):
        v.add((i, j))
        for di, dj in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
            if 0 <= i + di < m and 0 <= j + dj < n:
                if board[i + di][j + dj] == "O" and (i + di, j + dj) not in v:
                    self.DFS(board, v, i + di, j + dj, m, n)

    def solve(self, board: List[List[str]]) -> None:
        m = len(board)
        n = len(board[0])
        for i in range(m):
            for j in range(n):
                if board[i][j] == "O":
                    v = set()
                    self.DFS(board, v, i, j, m, n)
                    isEnclosed = True
                    for x, y in v:
                        if x == 0 or x == m - 1 or y == 0 or y == n - 1:
                            isEnclosed = False
                    if isEnclosed:
                        for x, y in v:
                            board[x][y] = "X"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)