problem
Analysisi Process
Notice in the explanation of the title that no O at any boundary is filled with X and we can imagine that all O that is not surrounded is directly or indirectly connected to O at the boundary and we can use this property to determine whether O is at the boundary, specifically
For each O on the boundary, we start with it and mark all O’s that are directly or indirectly related to it
Finally, we go through the matrix, for each letter: if the letter is marked, the letter is not surrounded by the letter X letter O, we restore it to the letter O;
If the letter is not marked, then the letter is an O surrounded by the letter X, which we change to the letter X
We can use depth-first search to implement the tag operation. In the following code, we change the marked letter O to the letter A
Code
golang
var n, m int
func solve(board [][]byte) {
//Determines whether a 2D array is empty
if len(board) == 0 || len(board[0]) == 0 {
return
}
//search and mark
n, m = len(board), len(board[0])
//Search from the edge to see if it's on the edge
for i := 0; i < n; i++ {
dfs(board, i, 0)
dfs(board, i, m - 1)
}
for i := 1; i < m - 1; i++ {
dfs(board, 0, i)
dfs(board, n - 1, i)
}
//To replace
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if board[i][j] == 'A' {
board[i][j] = 'O'
} else if board[i][j] == 'O' {
board[i][j] = 'X'
}
}
}
}
func dfs(board [][]byte, x, y int) {
//Border judgment
//board[x][y] == 'O' indicate that you have searched
if x < 0 || x >= n || y < 0 || y >= m || board[x][y] != 'O' {
return
}
//the O that goes with the boundary, replace it with a A, and then switch back to O
board[x][y] = 'A'
dfs(board, x + 1, y)
dfs(board, x - 1, y)
dfs(board, x, y + 1)
dfs(board, x, y - 1)
}
java
class Solution {
int n, m;
//Determines whether a 2D array is empty
public void solve(char[][] board) {
n = board.length;
if (n == 0) {
return;
}
//search and mark
m = board[0].length;
//Search from the edge to see if it's on the edge
for (int i = 0; i < n; i++) {
dfs(board, i, 0);
dfs(board, i, m - 1);
}
for (int i = 1; i < m - 1; i++) {
dfs(board, 0, i);
dfs(board, n - 1, i);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'A') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
public void dfs(char[][] board, int x, int y) {
//Border judgment
//board[x][y] == 'O' indicate that you have searched
if (x < 0 || x >= n || y < 0 || y >= m || board[x][y] != 'O') {
return;
}
//the O that goes with the boundary, replace it with a A, and then switch back to O
board[x][y] = 'A';
dfs(board, x + 1, y);
dfs(board, x - 1, y);
dfs(board, x, y + 1);
dfs(board, x, y - 1);
}
}