例题6-12 UVA Oil Deposits油田

简单的DFS 和那个上篇POJ 一样的题目!

#include
#include
#include
using namespace std;
const int maxn = 100 + 10;
int N,M;
char mep[maxn][maxn];
void dfs(int x,int y){
    mep[x][y] = '*';
    for (int dx = -1; dx <= 1; ++dx){
        for (int dy = -1; dy <= 1; ++dy){
            int nx = x + dx , ny = y + dy;
            if (nx >= 0 && nx < N && ny >= 0 && ny <= M && mep[nx][ny] == '@')dfs(nx,ny);
        }
    }
    return;
}
int solve(){
    int ans=0;
    for (int i = 0; i < N; ++i)
        for (int k = 0; k < M; ++k)
            if (mep[i][k] == '@'){dfs(i,k);++ans;}
    return ans;
}
int main()
{
    while(cin >> N >> M && N && M){
        getchar();
        for (int i = 0; i < N; ++i)gets(mep[i]);
        printf("%d\n",solve());
    }
    return 0;
}


你可能感兴趣的:(第六章,数据结构基础(例题))