AlgoMaster Logo

Surrounded Regions

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Simple DFS Approach

Intuition:

The problem can be approached using DFS to explore connected regions. The idea is to identify regions of 'O's connected to the boundary, which cannot be surrounded. All other 'O's can be flipped to 'X' as they are enclosed.

Steps:

  1. Traverse all boundary cells and run a DFS for each cell containing 'O'.
  2. In the DFS, mark every 'O' connected directly or indirectly as a safe entity (for example, temporarily replace 'O' with another character like '#').
  3. After marking, traverse the matrix again:
    • Convert the safe '#'' back to 'O'.
    • Change remaining 'O's to 'X'.

Code:

2. Optimized BFS Approach

Intuition:

Instead of using DFS to solve the problem, we can use BFS. Using BFS helps to avoid the potential maximum recursion depth reached issue seen with DFS, especially with large matrices.

Steps:

  1. Use a queue data structure to implement BFS for boundary 'O's.
  2. Process in the same manner as DFS.
  3. At the end, convert '#' back to 'O' and rest 'O' to 'X'.

Code:

3. Union-Find (Disjoint Set Union) Approach

Intuition:

Union-Find can be applied to efficiently manage connections. We can think of each cell as a node, and connect boundary 'O's to a dummy node as they can't be surrounded. All other unconnected 'O's are converted to 'X'.

Steps:

  1. Create a parent array for union-find.
  2. Connect every boundary 'O' to a dummy node.
  3. Connect internal 'O's with their neighbors if they are also 'O'.
  4. Finally, iterate over the board and change any 'O' not connected to the dummy node to 'X'.

Code: