-
Notifications
You must be signed in to change notification settings - Fork 13
/
flood-fill-example.cpp
173 lines (149 loc) · 3.66 KB
/
flood-fill-example.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#define S_MAX 30
struct Game
{
int w, h;
int t;
int ID;
bool end;
char data[S_MAX][S_MAX];
char tmp [S_MAX][S_MAX];
int time[S_MAX][S_MAX];
int id [S_MAX][S_MAX];
Game(int W=0, int H=0):w(W), h(H), t(1), ID(0), end(false) {}
void addLine(const string& line, int i)
{
for ( int j = 0; j < line.size(); j++ )
{
data[i][j] = line.at(j);
time[i][j] = ( line.at(j) == '.' || line.at(j) == '#' ) ? 0 : t;
id [i][j] = ( line.at(j) == '.' || line.at(j) == '#' ) ? 0 : ++ID;
}
}
void printState(void) const
{
for ( int i = 0; i<h; i++ )
{
for ( int j = 0; j<w; j++ )
{
cout << data[i][j];
}
cout << endl;
}
}
void printId (void) const
{
for ( int i = 0; i<h; i++ )
{
for ( int j = 0; j<w; j++ )
{
cerr << id[i][j];
}
cerr << endl;
}
}
void printTime(void) const
{
for ( int i = 0; i<h; i++ )
{
for ( int j = 0; j<w; j++ )
{
cerr << time[i][j];
}
cerr << endl;
}
}
void solve(void)
{
while ( !end )
{
diffuse();
}
}
void diffuse(void)
{
createTemp();
end = true;
++t;
for ( int i = 0; i<h; i++ )
{
for ( int j = 0; j<w; j++ )
{
char c = data[i][j];
int k = id [i][j];
if ( Game::isTroop(c) )
{
// Propagate North
if ( i > 0 ) propagate(i - 1 , j , c, k);
// Propagate South
if ( i < h-1) propagate(i + 1 , j , c, k);
// Propagate West
if ( j > 0 ) propagate(i , j - 1, c, k);
// Propagate East
if ( j < w-1) propagate(i , j + 1, c, k);
}
}
}
updateData();
}
void propagate ( int i, int j, char c, int k)
{
if ( data[i][j] != '#' )
{
if ( time[i][j] == 0 )
{
time[i][j] = t;
id [i][j] = k;
tmp [i][j] = c;
end = false;
}
else if ( time[i][j] == t )
{
if ( id[i][j] != k )
{
tmp [i][j] = '+';
id [i][j] = -1 ;
end = false;
}
}
}
}
void createTemp(void)
{
for ( int i = 0; i<h; i++ )
for ( int j = 0; j<w; j++ )
{
tmp[i][j] = data[i][j];
}
}
void updateData (void)
{
for ( int i = 0; i<h; i++ )
for ( int j = 0; j<w; j++ )
{
data[i][j] = tmp[i][j];
}
}
static bool isTroop(char c)
{
return ( (c != '.') && (c != '#') );
}
};
int main()
{
string line;
int width, height;
cin >> width >> height; cin.ignore();
Game game(width, height);
for ( int i = 0; i < height; i++ )
{
getline(cin, line);
game.addLine(line, i);
}
game.solve ();
game.printState();
}