leetcode笔记:37. sudoku solver

# Title Difficulty Topic
130 Surrounded Regions Medium Depth-first Search; Breadth-first Search; Union Find

Description

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
2
3
4
X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

1
2
3
4
X X X X
X X X X
X X X X
X O 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.

两次替换

先利用DFS将边缘的O替换为W。然后,再将内部的O替换为X,再将边缘的W替换为O

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class  {
public void solve(char[][] board) {
if(board == null || board.length == 0 ||
board[0] == null || board[0].length == 0) return;

for(int i=0; i<board.length; i++) {
replace(board, i, 0, 'W');
replace(board, i, board[0].length-1, 'W');
}
for(int j=0; j<board[0].length; j++) {
replace(board, 0, j, 'W');
replace(board, board.length-1, j, 'W');
}

for(int i=0; i<board.length; i++) {
for(int j=0; j<board[0].length; j++) {
if(board[i][j] == 'O') board[i][j] = 'X';
if(board[i][j] == 'W') board[i][j] = 'O';
}
}
}

public void replace(char[][] board, int i, int j, char later) {
if(i < 0 || i >= board.length ||
j < 0 || j >= board[0].length) return;
if(board[i][j] == 'X' || board[i][j] == later) return;
board[i][j] = later;
replace(board, i+1, j, later);
replace(board, i-1, j, later);
replace(board, i, j+1, later);
replace(board, i, j-1, later);
}
}