Skip to content

Commit 05da0a5

Browse files
Create 130-Surrounded-Regions.cs
1 parent fd08e46 commit 05da0a5

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Diff for: csharp/130-Surrounded-Regions.cs

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
public class Solution {
2+
public void Solve(char[][] board) {
3+
var n = board.Length;
4+
5+
if (n == 0) return;
6+
var m = board[0].Length;
7+
8+
for (int i = 0; i < n; i++) {
9+
for (int j = 0; j < m; j++) {
10+
if ((i == 0 || j == 0 || i == n - 1 || j == m - 1) && board[i][j] == 'O') {
11+
CaptureDfs(board, i, j);
12+
}
13+
}
14+
}
15+
16+
for (int i = 0; i < n; i++) {
17+
for (int j = 0; j < m; j++) {
18+
if (board[i][j] == 'O') {
19+
board[i][j] = 'X';
20+
}
21+
}
22+
}
23+
24+
for (int i = 0; i < n; i++) {
25+
for (int j = 0; j < m; j++) {
26+
if (board[i][j] == 'T') {
27+
board[i][j] = 'O';
28+
}
29+
}
30+
}
31+
}
32+
33+
private void CaptureDfs(char[][] board, int x, int y) {
34+
var n = board.Length;
35+
var m = board[0].Length;
36+
37+
if (x >= n || x < 0 || y >= m || y < 0) {
38+
return;
39+
}
40+
41+
if (board[x][y] == 'T' || board[x][y] == 'X') return;
42+
43+
board[x][y] = 'T';
44+
CaptureDfs(board, x+1, y);
45+
CaptureDfs(board, x-1, y);
46+
CaptureDfs(board, x, y+1);
47+
CaptureDfs(board, x, y-1);
48+
49+
}
50+
}

0 commit comments

Comments
 (0)