油田

油田

题目链接:https://vjudge.net/problem/ZOJ-1709

思路:

​ 多组输入直到输入00为止,输出油田的个数;利用dfs进行搜索。

代码:

#include <bits/stdc++.h>
using namespace std;

char a[105][105];
int b[8][2]={{-1,1},{0,1},{1,1},{-1,0},{1,0},{-1,-1},{0,-1},{1,-1}};//一个油田的上下左右以及左上,右下,左下,右上的八个方位;
int x,y,m,n;
void dfs(int x,int y)
{
    a[x][y] = '*';//防止重复搜索;
    int i,xx,yy;
    for(i=0;i<8;i++){
        xx = x + b[i][0];
        yy = y + b[i][1];
        if(xx<0||xx>=n||yy<0||yy>=m){
            continue;
        }
        if(a[xx][yy] == '@'){
            dfs(xx,yy);
        }
    }
}
int main()
{
   // freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int i,j,l=0;
    while(scanf("%d %d",&n,&m)&&n!=0&&m!=0){
        for(i=0;i<n;i++){
            scanf("%s",a[i]);
        }
        for(i=0;i<n;i++){
            for(j=0;j<m;j++){
                if(a[i][j] == '@'){
                    dfs(i,j);//如果八个方位有油田就继续搜索,没有就加一;
                    l++;
                }
            }
        }
        printf("%d\n",l);
        l = 0;
    }
    return 0;
}

参考文章:

https://blog.csdn.net/zenail501129/article/details/22759725

https://blog.csdn.net/alidadaaaa/article/details/79723800

posted @ 2019-08-01 19:23  幽灵小一只  阅读(100)  评论(0编辑  收藏  举报