每日一题 2019 - 05 - 04
题目:
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'
,其实就是在做图的深度优先搜索,不过需要注意一点的是:为了节省时间,可以只对边界上且为'O'
的位置进行搜索,对符合条件的'O'
将其转换为'$'
,对不满足要求的'O'
不做处理,最后将除了为'$'
外的所有位置均置为'X'
,将标记为'$'
位置的元素置为'0'
,同时需要对该位置的上下左右同时进行搜索,要注意访问的位置不能越界与小于0;
代码:
1 | class Solution { |