forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0130-surrounded-regions.cs
50 lines (41 loc) · 1.25 KB
/
0130-surrounded-regions.cs
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 Solution {
public void Solve(char[][] board) {
var n = board.Length;
if (n == 0) return;
var m = board[0].Length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if ((i == 0 || j == 0 || i == n - 1 || j == m - 1) && board[i][j] == 'O') {
CaptureDfs(board, i, j);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'T') {
board[i][j] = 'O';
}
}
}
}
private void CaptureDfs(char[][] board, int x, int y) {
var n = board.Length;
var m = board[0].Length;
if (x >= n || x < 0 || y >= m || y < 0) {
return;
}
if (board[x][y] == 'T' || board[x][y] == 'X') return;
board[x][y] = 'T';
CaptureDfs(board, x+1, y);
CaptureDfs(board, x-1, y);
CaptureDfs(board, x, y+1);
CaptureDfs(board, x, y-1);
}
}