Description
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.
Example:
1 | X X X X |
After running your function, the board should be:
1 | X X X X |
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O'
on the border of the board are not flipped to 'X'
. Any 'O'
that is not on the border and it is not connected to an 'O'
on the border will be flipped to 'X'
. Two cells are connected if they are adjacent cells connected horizontally or vertically.
解法
如果直接从一个’O’开始搜索判断是不是会到达边界,将会非常麻烦,因为需要保存路径上的每个’O’,如果到达边界就放弃这片区域的所有值,否则将其变为’X’。有一种更为聪明的做法是从四个边界出发,用DFS算法将从边界开始的’O’的区域都变成另外一个临时的值,这样做完之后剩下的‘O’将会是被包围的,然后将其变为‘X’,再将临时的值变为’O’即可。
具体代码如下:
1 | class Solution { |