board is an m × n grid where every cell is "X" or "O". Two "O" cells belong to the same region when you can walk from one to the other through "O" cells, stepping only up, down, left or right (never diagonally).
A region is surrounded when none of its cells lies on the outer edge of the board: it is closed in by "X" cells on every side. Capture every surrounded region by turning all of its cells into "X". A region with even one cell on the edge stays exactly as it is.
Change board itself. Your function returns nothing; the answer judged is board after your function has run.
The two "O"s in the second column form a region that reaches the top edge, so they stay. The three "O"s on the right form a region that touches no edge, so all three are captured.
The centre "O" only touches the corners diagonally, so it is a region of its own, and it is surrounded. Each corner is a region on the edge and stays.
Constraints
m == board.lengthn == board[i].length1 <= m, n <= 200board[i][j] is "X" or "O".Turn the question around: instead of asking which regions are surrounded, find the ones that are not. Every "O" connected to an "O" on the edge survives; every other "O" is captured.
A region is safe as soon as one of its cells sits on the edge of the board. So whether an "O" gets captured isn't about its own neighbours. It's about whether some walk over "O" cells leads from it to the edge.
Time O(m · n)Space O(m · n)
The full walkthrough and code are part of Premium