Graphs · Pattern 5 of 14

The complement trick: search from the border

Finding what is trapped is hard; finding what escapes is easy. DFS from every border cell to mark the safe cells, then everything left unmarked is the answer.

1 variation · 1 problem · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Cells that are fully surrounded, enclosed or cannot reach the edge
  • Capture, flip or count regions that do not touch the border

The template

DFS - Complement Trick
void solve(char[][] board) {
    int m = board.length, n = board[0].length;
    for (int r = 0; r < m; r++) { mark(board, r, 0); mark(board, r, n - 1); }
    for (int c = 0; c < n; c++) { mark(board, 0, c); mark(board, m - 1, c); }
    for (int r = 0; r < m; r++)
        for (int c = 0; c < n; c++)
            board[r][c] = board[r][c] == '#' ? 'O' : 'X';   // safe back to O, the rest is captured
}

// DFS from the border: every O reached here can escape
void mark(char[][] b, int r, int c) {
    if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] != 'O') return;
    b[r][c] = '#';
    mark(b, r + 1, c); mark(b, r - 1, c); mark(b, r, c + 1); mark(b, r, c - 1);
}

The variations

  1. 1Mark what escapes, flip the rest

    Every O connected to the border survives. Flood from the four edges and mark those cells, then one pass turns marked cells back into O and every other O into X.

Mistakes to avoid

  • Flipping a region as soon as you find it, before you know whether it touches the border. Mark the safe cells first, flip at the end.
  • Using a third marker that already appears in the input. Pick a character (like #) the board never contains.
Next: Multi-source BFS: spread from many starts at once →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.