Surrounded regions
Challenge · Write code · about 20 min
A board holds 1 for an O cell and 0 for an X cell. A group of O cells joined up, down, left or right is captured when no O cell of the group is on the border of the board.
Return the board after every captured O has been flipped to 0. Cells that are not captured stay as they are.
Example 1
Input:
[[[0,0,0,0],[0,1,1,0],[0,0,1,0],[0,1,0,0]]]
Output:
[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,1,0,0]]
The three O cells in the middle are captured.
Example 2
Input:
[[[1,1],[1,1]]]
Output:
[[1,1],[1,1]]
Every cell is on the border.
Constraints
- 1 ≤ rows, cols ≤ 50
- board[r][c] is 0 or 1
Learn the idea first: Connected components and flood fill, a visual lesson.
More Connected components and flood fill problems
- Label the components Warm-up
- Number of islands Standard
- Max area of island Standard
- Count components Standard