Surrounded Regions - Matrix and Grid Traversal Pattern

Surrounded Regions in Java using the Matrix and Grid Traversal pattern: problem statement, approach, template, complexity, and interview tips.

Surrounded Regions

Problem Statement

Capture all 'O' regions in a board that are fully surrounded by 'X'.

Pattern: Matrix and Grid Traversal

Treat a 2D grid as a graph where each cell connects to its four (or eight) neighbours and traverse it with DFS or BFS.

Use this pattern when the input is a grid of cells and you count regions, fill areas, or find reachable cells.

Approach

  1. Define the direction array and the bounds check.
  2. Start a DFS or BFS from each unvisited cell of interest.
  3. Mark cells visited (or mutate the grid) to avoid revisiting.

Pattern Template (Java)

int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void dfs(int[][] grid, int r, int c) {
    if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length) return;
    // return if the cell is invalid or already visited, then mark it
    for (int[] d : dirs) {
        dfs(grid, r + d[0], c + d[1]);
    }
}

Adapt this template to the exact rules of Surrounded Regions: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(rows x cols) time and space in the worst case.

Interview Tips

  • Confirm whether you may modify the input grid.
  • For border-based problems, start the search from the border cells.
  • Start with a brute-force idea, state its complexity, then explain how the Matrix and Grid Traversal pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Number of Islands | Next: Pacific Atlantic Water Flow

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.