Wednesday, March 19, 2014

LeetCode: Surrounded Regions


Given a 2D board containing 'X' and '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,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X

Solution:
这道题本身不难,关键是逆向思维,先从四个边界开始找‘O’, 找到后换成'D', 用一个queue递归扫描所有连通区域,最后凡是没有没有变成D的O都是被X包围的;注意点是二维数组的操作,code如下:

No comments:

Post a Comment