Surrounded Regions

Surrounded Regions – Medium Level Problem

You are given a 2D grid (matrix) with the characters ‘X’ and ‘O’.

If a group of ‘O’s is completely enclosed by ‘X’s on all four sides (up, down, left, and right), it is considered surrounded.

Your task is to replace all such surrounded ‘O’s with ‘X’s directly in the given grid. Make the changes without using extra space for another grid.

Surround Regions

Example 1:

Example of Surrounded Region

Explanation: Note that regions that are on the border are not considered surrounded regions.

Constraints :

  • 1 <= board.length, board[i].length <= 200
  • board[i][j] is ‘X’ or ‘O’.

Surrounded Regions Problem - Solution

Recommendation for Time and Space Complexity – Aim for a solution with O(m * n) time and O(m * n) space, where m is the number of rows and n is the number of columns in the grid.

Hints for solving problems

Hint 1

Focus on regions of ‘O’ that are not connected to the border. These are the ones surrounded by ‘X’. Think about how to identify which ‘O’s are connected to the border.

Hint 2

Use Depth First Search (DFS). Instead of finding surrounded regions directly, mark the regions connected to border ‘O’s to separate them.

Hint 3

Run DFS from every border ‘O’, marking connected cells with ‘#’. After that, traverse the grid:

  • Convert remaining ‘O’s to ‘X’ (surrounded regions).
  • Convert ‘#’ back to ‘O’ (border-connected regions).

There are mainly 3 approach to solve this problem-

  1. Depth First Search Method
  2. Breadth First Search Method

1. Depth First Search Method

Use DFS to explore all ‘O’s connected to the border and mark them temporarily (e.g., as ‘#’). After the DFS traversal, convert the remaining ‘O’s (surrounded) to ‘X’, and revert ‘#’ back to ‘O’.

  • Time complexity: O(m * n)
  • Space complexity: O(m * n)

where m is the number of rows and n is the number of columns of the board.

Code

2. Breadth First Search Method

Similar to DFS, use BFS starting from all border ‘O’s to mark the connected regions with a temporary marker (e.g., ‘#’). Finally, update the grid by flipping the remaining ‘O’s to ‘X’ and reverting ‘#’ to ‘O’.

  • Time complexity: O(m * n)
  • Space complexity: O(m * n)

where m is the number of rows and n is the number of columns of the board.

Code

More Articles