Problem 276
Surrounded Regions
Medium · 20 pts · Matrix, Depth-First Search, Breadth-First Search
Problem
A grid contains the letters 'X' and 'O'. A region is a group of 'O' cells connected up, down, left or right. A region that touches the border of the grid cannot be surrounded, so it stays as it is. Every other region is completely enclosed by 'X' and is captured: all its cells become 'X'. Print the grid after capturing. Work backwards from the border: run BFS or DFS from every 'O' on the border and mark everything reachable as safe. Afterwards, turn every 'O' that is not marked safe into 'X'.
Input
First line: R and C. Next R lines: C characters, each 'X' or 'O'.
Output
Print the R resulting rows.
Constraints
1 <= R, C <= 200
Example input
4 4 XXXX XOOX XXOX XOXX
Example output
XXXX XXXX XXXX XOXX
Explanation
The region of three O's in the middle (two in the second row and one in the third) does not touch the border, so it becomes X. The O in the bottom row touches the border and stays an O.