题目地址:
https://www.lintcode.com/problem/surrounded-regions/description
给定一个由 X X X与 O O O组成的二维矩阵,要求将被 X X X包围的 O O O改为 X X X。但是不包含边界包围的 O O O。
可以用DFS。先遍历边界,对边界上的 O O O做DFS,将其标记为其他符号,比如标记为 # \# #,然后再将其余的 O O O变为 X X X,再将所有的 # \# #变为 O O O。代码如下:
public class Solution {
/*
* @param board: board a 2D board containing 'X' and 'O'
* @return: nothing
*/
public void surroundedRegions(char[][] board) {
// write your code here
if (board == null || board.length == 0 || board[0].length == 0) {
return;
}
int m = board.length, n = board[0].length;
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// 对左右边界的O进行DFS,连通块标记为#
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') {
dfs(i, 0, board, '#', dirs);
}
if (board[i][n - 1] == 'O') {
dfs(i, n - 1, board, '#', dirs);
}
}
// 对上下边界的O进行DFS,连通块标记为#
for (int i = 0; i < n; i++) {
if (board[0][i] == 'O') {
dfs(0, i, board, '#', dirs);
}
if (board[m - 1][i] == 'O') {
dfs(m - 1, i, board, '#', dirs);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
if (board[i][j] == '#') {
board[i][j] = 'O';
}
}
}
}
private void dfs(int x, int y, char[][] board, char to, int[][] dirs) {
board[x][y] = to;
for (int i = 0; i < dirs.length; i++) {
int nextX = x + dirs[i][0], nextY = y + dirs[i][1];
if (inBound(nextX, nextY, board) && board[nextX][nextY] == 'O') {
dfs(nextX, nextY, board, to, dirs);
}
}
}
private boolean inBound(int x, int y, char[][] board) {
return 0 <= x && x < board.length && 0 <= y && y < board[0].length;
}
}
时空复杂度 O ( m n ) O(mn) O(mn)。