Surrounded Regions
DFS
Last updated
Was this helpful?
DFS
Last updated
Was this helpful?
Given a 2D board containing 'X'
and 'O'
(the letter O), capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
Have to use DFS since we are dealing with connected components here. The important part is the connected components that will be using DFS on are the border 'O' and the other 'O' that are connected to them.
Use DFS on the borders to find all the connected 'O' and initally chage all these connected components to something else to denote the connectivity to the border 'O' (like change them to 'C')
After all the border DFS is completed, run back through the board and change all 'C' to 'O'. The original 'O' 's that weren't changed to 'C' are the valid regions that can be flipped. So we flip these to 'X'.
Time: O(m*n)
Space: O(m*n)