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.
For example,
After running your function, the board should be:
解法1: DFS
|
|
解法2: BFS
这题DFS的解法非常容易出现stack overflow。 主要的原因是在判断对那个方向进行DFS的时候如果不避免边界上的点的话就会overflow,所以我们要跳过那些边界的点而只看纵深的点。如果用BFS的话情况会好不少,不过要写对也不容易。基本思路也是对于边界上的O点,使用BFS把所有相通的都标注一下。
不过在进行BFS的时候,每一个新的点push进queue的时候,立即把他标注成M,这样可以减少push的点。