forked from RajwardhanShinde/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSurroundedRegions.cpp
29 lines (28 loc) · 1.05 KB
/
SurroundedRegions.cpp
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
class Solution {
public:
void solve(vector<vector<char>>& board) {
if (board.empty()) return;
int row = board.size(), col = board[0].size();
for (int i = 0; i < row; ++i) {
check(board, i, 0); // first column
check(board, i, col - 1); // last column
}
for (int j = 1; j < col - 1; ++j) {
check(board, 0, j); // first row
check(board, row - 1, j); // last row
}
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j)
if (board[i][j] == 'O') board[i][j] = 'X';
else if (board[i][j] == '1') board[i][j] = 'O';
}
void check(vector<vector<char>>& board, int i, int j) {
if (board[i][j] == 'O') {
board[i][j] = '1';
if (i > 1) check(board, i - 1, j);
if (j > 1) check(board, i, j - 1);
if (i + 1 < board.size()) check(board, i + 1, j);
if (j + 1 < board[0].size()) check(board, i, j + 1);
}
}
};