Given an m×n board of 'X' and 'O', capture every region of 'O' that is fully surrounded by 'X' (not connected to the border) by flipping it to 'X'. Modify the board in place.
Same idea with one multi-source BFS: seed the queue with every border 'O', spread through 'O' neighbors, then flip what was never reached.
1function solve(board: string[][]): void {2const m = board.length, n = board[0].length, queue: number[][] = [];3for (let r = 0; r < m; r++) for (let c = 0; c < n; c++)4if ((r === 0 || c === 0 || r === m - 1 || c === n - 1) && board[r][c] === "O") { board[r][c] = "S"; queue.push([r, c]); }5while (queue.length) {6const [r, c] = queue.shift()!;7for (const [x, y] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]])8if (x >= 0 && y >= 0 && x < m && y < n && board[x][y] === "O") { board[x][y] = "S"; queue.push([x, y]); }9}10for (let r = 0; r < m; r++) for (let c = 0; c < n; c++)11board[r][c] = board[r][c] === "S" ? "O" : "X";12}
| X | X | X | X |
| X | O | O | X |
| X | X | O | X |
| X | S | X | X |
Seed the queue with 1 border 'O' cells.
Space: play/pause · ←/→: step