26 · Graphs: BFS & DFS

#130 Surrounded Regions

Mediumsolve on LeetCode ↗

frequently reported atGoogleBloombergUberByteDance / TikTok

the problem

In plain words

A board holds 'X' and 'O'. Capture every region of 'O's that is completely surrounded by 'X's (4 directions) by flipping it to 'X'. Regions touching the border survive. Modify the board in place.

in board = [[X,X,X,X],[X,O,O,X],[X,X,O,X],[X,O,X,X]]

out [[X,X,X,X],[X,X,X,X],[X,X,X,X],[X,O,X,X]]

The bottom 'O' touches the border, so it is not captured.

in board = [[X]]

out [[X]]

  • 1 ≤ m, n ≤ 200
  • board[i][j] is 'X' or 'O'

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #417
    2. #200
      Number of Islands
      Mediumin Graphs
    3. #733
      Flood Fill
      Easyin Graphs