-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path130.被围绕的区域.cpp
125 lines (109 loc) · 2.6 KB
/
130.被围绕的区域.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
/*
* @lc app=leetcode.cn id=130 lang=cpp
*
* [130] 被围绕的区域
*/
// @lc code=start
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class UF{
public:
int count;
vector<int> parent;
vector<int> size;
UF(int n){
count = n;
parent = vector<int>(n+1, 0);
size = vector<int>(n+1, 0);
for(int i=0;i<=n;i++){
parent[i] = i;
size[i] = 1;
}
}
void Union(int p, int q){
int rootP = find(p);
int rootQ = find(q);
if(rootP == rootQ){
return;
}
if(size[rootP] > size[rootQ]){
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}else{
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
count--;
}
bool connected(int p, int q){
int rootP = find(p);
int rootQ = find(q);
return rootP == rootQ;
}
int find(int x){
while(parent[x]!=x){
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
};
class Solution {
public:
void solve(vector<vector<char>>& board) {
int m = board.size();
if(m==0)return;
int n = board[0].size();
UF uf(m*n + 1);
int dummy = m*n;
for(int i=0;i<m;i++){
if(board[i][0] == 'O'){
uf.Union(i * n, dummy);
}
if(board[i][n-1]=='O'){
uf.Union(i * n + n - 1, dummy);
}
}
for(int j = 0;j<n;j++)
{
if(board[0][j] == 'O'){
uf.Union(j, dummy);
}
if(board[m-1][j] == 'O'){
uf.Union(n * (m - 1) + j, dummy);
}
}
vector<vector<int> > dir = {
{1, 0}, {0, 1}, {0, -1}, {-1, 0}
};
for(int i=1;i<m-1;i++)
{
for(int j=1;j<n-1;j++)
{
if(board[i][j]=='O')
{
for(int k = 0; k<4;k++){
int x = i + dir[k][0];
int y = j + dir[k][1];
if(board[x][y] == 'O'){
uf.Union(x * n + y, i * n + j);
}
}
}
}
}
for(int i=1;i<m-1;i++)
{
for(int j=1;j<n-1;j++)
{
if(!uf.connected(i * n + j, dummy))
{
board[i][j] = 'X';
}
}
}
}
};
// @lc code=end