-
Notifications
You must be signed in to change notification settings - Fork 0
/
130surroundregions.cpp
136 lines (117 loc) · 2.83 KB
/
130surroundregions.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//
//Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
//
//A region is captured by flipping all 'O's into 'X's in that surrounded region.
//
//For example,
//
//X X X X
//X O O X
//X X O X
//X O X X
//
//
//
//After running your function, the board should be:
//X X X X
//X X X X
//X X X X
//X O X X
//
// correct dfs, however failed at stack overflow to causing run time error
void solve_fill_helper1(vector<vector<char>>& board, int x, int y)
{
board[x][y] = 'd';
if ( x > 0 && board[x-1][y] == 'O')
{
solve_fill_helper1(board, x-1, y);
}
if ( x+1 < board.size() && board[x+1][y] == 'O')
{
solve_fill_helper1(board, x+1, y);
}
if ( y > 0 && board[x][y-1] == 'O')
{
solve_fill_helper1(board, x, y-1);
}
if ( y+1 < board[0].size() && board[x][y+1] == 'O')
{
solve_fill_helper1(board, x, y+1);
}
}
// use BFS instead to avoid stack overflow
void solve_fill_helper2(vector<vector<char>>& board, int i, int j)
{
stack<pair<int, int>>stk;
stk.push(make_pair(i, j));
while(!stk.empty())
{
int x =stk.top().first;
int y =stk.top().second;
stk.pop();
board[x][y] = 'd';
if ( x > 0 && board[x-1][y] == 'O')
{
stk.push(make_pair(x-1, y));
}
if ( x+1 < board.size() && board[x+1][y] == 'O')
{
stk.push(make_pair(x+1, y));
}
if ( y > 0 && board[x][y-1] == 'O')
{
stk.push(make_pair(x, y-1));
}
if ( y+1 < board[0].size() && board[x][y+1] == 'O')
{
stk.push(make_pair(x, y+1));
}
}
}
class Solution {
public:
void solve(vector<vector<char>>& board)
{
if (0 == board.size() || 0 == board[0].size())
{
return;
}
int n = board.size(), m = board[0].size();
for ( int i = 0; i < n; i++)
{
if ( board[i][0] == 'O')
{
solve_fill_helper2(board, i, 0);
}
if ( board[i][m-1] == 'O')
{
solve_fill_helper2(board, i, m-1);
}
}
for ( int i = 0; i < m; i++)
{
if ( board[0][i] == 'O')
{
solve_fill_helper2(board, 0, i);
}
if ( board[n-1][i] == 'O')
{
solve_fill_helper2(board, n-1, i);
}
}
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < m; j++)
{
if ( board[i][j] != 'd')
{
board[i][j] = 'X';
}
else
{
board[i][j] = 'O';
}
}
}
}
};