-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC_130.java
50 lines (48 loc) · 1.66 KB
/
LC_130.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class LC_130 {
static int[][] move = new int[][]{{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
static boolean[][] visited;
public void solve(char[][] board) {
int m = board.length;
int n = board[0].length;
visited = new boolean[m][n];
if (m < 3 || n < 3) return;
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') {
visited[i][0] = true;
dfs(i, 0, board);
}
if (board[i][n - 1] == 'O') {
visited[i][n - 1] = true;
dfs(i, n - 1, board);
}
}
for (int j = 0; j < n; j++) {
if (board[0][j] == 'O') {
visited[0][j] = true;
dfs(0, j, board);
}
if (board[m - 1][j] == 'O') {
visited[m - 1][j] = true;
dfs(m - 1, j, board);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') board[i][j] = 'X';
else if (board[i][j] == 'A') board[i][j] = 'O';
}
}
}
public static void dfs(int x, int y, char[][] board) {
board[x][y] = 'A';
for (int[] dir : move) {
int nextX = x + dir[0];
int nextY = y + dir[1];
if (nextX < 0 || nextX > board.length - 1 || nextY < 0 || nextY > board[0].length - 1) continue;
if (!visited[nextX][nextY] && board[nextX][nextY] == 'O') {
visited[nextX][nextY] = true;
dfs(nextX, nextY, board);
}
}
}
}