Fork me on GitHub

Surrounded Region

Linkage

https://leetcode.com/problems/surrounded-regions/description/

Code

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
class Solution {
public void solve(char[][] board) {
int row_number = board.length;
if (row_number == 0) return;
int col_number = board[0].length;

for (int i = 0; i < row_number; i++){
search(board, i, 0);
search(board, i, col_number - 1);
}

for (int j = 0; j < col_number; j++){
search(board, 0, j);
search(board, row_number - 1, j);
}

for (int i = 0; i < row_number; i++){
for(int j = 0; j < col_number; j++){
if(board[i][j] != 'M')
board[i][j] = 'X';
else
board[i][j] = 'O';
}
}
}

public void search(char[][] board, int i, int j) {
int row_number = board.length;
int col_number = board[0].length;
if (i < 0 || i >= row_number || j < 0 || j >= col_number || board[i][j] != 'O')
return;

board[i][j] = 'M';

int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for(int direction = 0; direction < 4; direction++){
int row = i + directions[direction][0];
int col = j + directions[direction][1];
search(board, row, col);
}
return;
}

}