UVa572

題目:
https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=513

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
#include <bits/stdc++.h>
using namespace std;

char mp[105][105] = {};
bool passed[105][105] = {false};
int row, col;

int dx[] = {0, 1, 1, 1, 0, -1, -1, -1};
int dy[] = {1, 1, 0, -1, -1, -1, 0, 1};

// 遞迴版
void nextPos(int x, int y) {
passed[x][y] = true;
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];

if (nx >= 0 && nx < row && ny >= 0 && ny < col && mp[nx][ny] == '@' && !passed[nx][ny]) {
nextPos(nx, ny);
}
}
}

// dfs版,用stack實作
void dfs(int i, int j){
passed[i][j] = true;
stack<pair<int, int>> st;
st.push({i, j});
while(!st.empty()){
pair<int, int> curr = st.top();
st.pop();

for(int i=0; i<8; ++i){
int nx = curr.first + dx[i];
int ny = curr.second + dy[i];

if(nx < row && nx >= 0 && ny < col && ny >= 0 && mp[nx][ny] == '@' && !passed[nx][ny]){
passed[nx][ny] = true;
st.push({nx, ny});
}
}
}
}

// bfs版,用queue實作
void bfs(int i, int j){
passed[i][j] = true;
queue<pair<int, int>> q;
q.push({i, j});

while(!q.empty()){
pair<int, int> curr = q.front();
q.pop();

for(int i=0; i<8; ++i){
int nx = curr.first + dx[i];
int ny = curr.second + dy[i];

if(nx < row && nx >= 0 && ny < col && ny >= 0 && mp[nx][ny] == '@' && !passed[nx][ny]){
passed[nx][ny] = true;
q.push({nx, ny});
}
}
}
}

int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
while(cin >> row >> col && row != 0){
for(int i=0; i<row; ++i){
for(int j=0; j<col; ++j){
cin >> mp[i][j];
passed[i][j] = false;
}
}
int oilCounts = 0;

for(int i=0; i<row; ++i){
for(int j=0; j<col; ++j){
if(mp[i][j] == '@' && !passed[i][j]){
++oilCounts;
// nextPos(i, j);
// dfs(i, j);
bfs(i, j);
}
passed[i][j] = true;
}
}

cout << oilCounts << '\n';
}
return 0;
}