-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurroundedRegions.cpp
More file actions
49 lines (45 loc) · 1.42 KB
/
surroundedRegions.cpp
File metadata and controls
49 lines (45 loc) · 1.42 KB
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
// Source: https://leetcode.com/problems/surrounded-regions/
// Author: Miao Zhang
// Date: 2021-01-20
class Solution {
public:
void solve(vector<vector<char>>& board) {
if (board.empty()) return;
int m = board.size();
int n = board[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
if (board[i][j] == 'O') {
dfs(board, i, j);
}
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
if (board[i][j] == '#') {
board[i][j] = 'O';
}
}
}
}
void dfs(vector<vector<char>>& board, int i, int j) {
board[i][j] = '#';
vector<pair<int, int>> dirs;
dirs.push_back(make_pair(1, 0));
dirs.push_back(make_pair(-1, 0));
dirs.push_back(make_pair(0, 1));
dirs.push_back(make_pair(0, -1));
for (auto d: dirs) {
int x = i + d.first;
int y = j + d.second;
if (x >= 0 && x < board.size() && y >= 0 && y < board[0].size() && board[x][y] == 'O') {
dfs(board, x, y);
}
}
}
};