Skip to content

Commit e2eb0bb

Browse files
committed
Create: 0130-surrounded-regions.dart
1 parent 636aab3 commit e2eb0bb

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

dart/0130-surrounded-regions.dart

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
late List<List<String>> board;
3+
late int rows;
4+
late int columns;
5+
6+
bool isInBound(int row, int column) {
7+
return 0 <= row && row < rows && 0 <= column && column < columns;
8+
}
9+
10+
void dfs(int row, int column) {
11+
if (!isInBound(row, column) || board[row][column] != 'O') {
12+
return;
13+
}
14+
15+
board[row][column] = 'T';
16+
17+
dfs(row + 1, column);
18+
dfs(row, column + 1);
19+
dfs(row - 1, column);
20+
dfs(row, column - 1);
21+
}
22+
23+
void solve(List<List<String>> board) {
24+
this.board = board;
25+
rows = board.length;
26+
columns = board[0].length;
27+
28+
// Traverse the first and last columns
29+
for (int column = 0; column < columns; column++) {
30+
dfs(0, column);
31+
dfs(rows - 1, column);
32+
}
33+
34+
// Traverse the first and last rows
35+
for (int row = 0; row < rows; row++) {
36+
dfs(row, 0);
37+
dfs(row, columns - 1);
38+
}
39+
40+
// Replace all 'O' with 'X' and 'T' back to 'O'
41+
for (int row = 0; row < rows; row++) {
42+
for (int column = 0; column < columns; column++) {
43+
if (board[row][column] == 'O') {
44+
board[row][column] = 'X';
45+
} else if (board[row][column] == 'T') {
46+
board[row][column] = 'O';
47+
}
48+
}
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)