问题描述
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/a4a880b1a1678387b24d7723853f432e.png)
问题分析
- 该题和小岛问题 LeetCode 200. Number of Islands 类似,都是要从一个位置开始,向四周扩散,对“连通区域”进行染色。只不过小岛问题染得是与原数组相对应的
visited
数组,该题直接染得是原数组。 - 染色最常用 DFS, 也可以用 BFS.
- 该题具体思路如下(算是逆向思维吧):
- 遍历四条边界,将边界上是
‘O’
并且与该‘O’
相连通(也等于‘O’
)的区域染成 ‘#’ - 然后遍历整个数组,将
‘O’
变为 ‘X’
,将 ‘#’
变为 ‘O’
,注意变化顺序。
经验教训
- 如何利用 DFS 对 对“连通区域”进行染色
- 该题与小岛问题综合比较
- 逆向思维考虑问题!!!
代码实现
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
return;
}
int row = board.length;
int col = board[0].length;
for (int j = 0; j < col; ++j) {
dfs(board, 0, j);
dfs(board, row - 1, j);
}
for (int i = 0; i < row; ++i) {
dfs(board, i, 0);
dfs(board, i, col - 1);
}
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
if (board[i][j] == '#') {
board[i][j] = 'O';
}
}
}
return;
}
public void dfs(char[][] board, int x, int y) {
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || board[x][y] != 'O') {
return;
}
board[x][y] = '#';
dfs(board, x - 1, y);
dfs(board, x + 1, y);
dfs(board, x , y - 1);
dfs(board, x, y + 1);
return;
}
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
return;
}
int row = board.length;
int col = board[0].length;
for (int j = 0; j < col; ++j) {
bfs(board, 0, j);
bfs(board, row - 1, j);
}
for (int i = 0; i < row; ++i) {
bfs(board, i, 0);
bfs(board, i, col - 1);
}
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
board[i][j] = board[i][j] == '#' ? 'O' : 'X';
}
}
return;
}
public void bfs (char[][] board, int x, int y) {
LinkedList<Position> queue = new LinkedList<>();
queue.add(new Position(x, y));
while (! queue.isEmpty()) {
Position pos = queue.remove();
int curX = pos.x;
int curY = pos.y;
if (curX >= 0 && curX < board.length && curY >= 0 && curY < board[0].length && board[curX][curY] == 'O') {
board[curX][curY] = '#';
queue.add(new Position(curX - 1, curY));
queue.add(new Position(curX + 1, curY));
queue.add(new Position(curX, curY - 1));
queue.add(new Position(curX, curY + 1));
}
}
return;
}
class Position {
int x;
int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
}