题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1241
代码:
#include <iostream>
#include <cstring>
using namespace std;
int m,n;
char oil[110][110];
void dfs(int r, int c){
//不符合条件则返回
if(r < 0 || r >= m || c < 0 || c >=n) return;
if(oil[r][c] != '@') return;
//将该油田标记已搜索过
oil[r][c] = '*';
//八个方向搜索
for(int i = -1; i <= 1; i++){
for(int j = -1; j <= 1; j++){
if(oil[r+i][c+j] == '@' && (i != 0 || j != 0)){
dfs(r+i, c+j);
}
}
}
}
int main(){
while(cin >> m >> n && m != 0){
//清空数组
memset(oil,0,sizeof(oil));
for(int i = 0; i < m; i++){
cin >> oil[i];
}
//设置计数器并初始化
int count = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(oil[i][j] == '@'){
//找到油田,开始搜索
dfs(i,j);
count++;
}
}
}
cout << count << endl;
}
return 0;
}