130 Surrounded Regions

1. Question

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,

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

2. Implementation

(1) Union Find

思路:

(1) 用Union Find的方法,将 n * m作为一个特殊的parent id,表示所有与边连接的component的root

(2) 对于board上所有"O",如果它在边上,则与 n * m的parent id union,否则将其四周的'O‘, 与其union

(3)

3. Time & Space Complexity

BFS: 时间复杂度O(mn), union-find中的函数时间复杂度接近常数, 空间复杂度O(mn), m和n分别为board的行数和列数

Last updated

Was this helpful?