Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Key Insight: Instead of finding surrounded regions directly, find the regions that are NOT surrounded (connected to the border) and mark them as safe. Everything else gets captured.
Algorithm:
Why this works: An 'O' is NOT surrounded if and only if there's a path of 'O's connecting it to the border. DFS from border cells finds exactly these.
Example:
X X X X X X X X
X O O X -> X X X X
X X O X X X X X
X O X X X O X X
The bottom 'O' touches the border, so it's not captured. The interior 'O's are all captured.
board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]][["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]board = [["X"]][["X"]]m == board.lengthn == board[i].length1 <= m, n <= 200board[i][j] is 'X' or 'O'.Click "Run" to execute your code against test cases
Socratic guidance - I'll ask questions, not give answers