Skip to content

Commit 4eba4bb

Browse files
committed
Create Surrounded Regions
1 parent 04b7d0b commit 4eba4bb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Matrix/Surrounded Regions

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// 想到了开头,没有想到细节。。。
2+
3+
class Solution {
4+
void bfs(int x,int y,vector<vector<char>> &board)
5+
{
6+
queue<int> q;
7+
visited(x,y,board,q);
8+
while(!q.empty())
9+
{
10+
int pos = q.front();
11+
q.pop();
12+
int posX = pos / board[0].size();
13+
int posY = pos % board[0].size();
14+
visited(posX-1,posY,board,q);
15+
visited(posX + 1,posY,board,q);
16+
visited(posX,posY-1,board,q);
17+
visited(posX,posY + 1,board,q);
18+
19+
}
20+
21+
}
22+
23+
void visited(int x, int y,vector<vector<char>> &board,queue<int>&q)
24+
{
25+
const int m = board.size();
26+
const int n = board[0].size();
27+
if(x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O')
28+
return;
29+
board[x][y] = '#'; // 这个很聪明~
30+
q.push(x * n + y);
31+
32+
}
33+
34+
public:
35+
void solve(vector<vector<char>> &board) {
36+
if(board.size() <= 0) return;
37+
int n = board.size();
38+
39+
int m = board[0].size();
40+
// 上下左右
41+
for(int i = 0;i < m;i++)
42+
{
43+
bfs(0,i,board);
44+
bfs(n-1,i,board);
45+
}
46+
for(int j = 1;j < n-1;j++)
47+
{
48+
bfs(j,0,board);
49+
bfs(j,m-1,board);
50+
}
51+
52+
for( int i = 0;i < n;i++)
53+
for(int j = 0;j < m;j++)
54+
{
55+
if(board[i][j] == '#')
56+
board[i][j] = 'O';
57+
else
58+
if(board[i][j] == 'O')
59+
board[i][j] = 'X';
60+
}
61+
62+
}
63+
};

0 commit comments

Comments
 (0)