今天,你惹对象生气了吗

今天,你惹对象生气了吗

题目链接:https://ac.nowcoder.com/acm/contest/298/B

思路:

​ 先对可以采的花进行覆盖,再用dfs进行搜索。

代码:

#include <bits/stdc++.h>
using namespace std;
char a[100][100];
int n,m,x,y;
int b[4][2]={{0,1},{-1,0},{1,0},{0,-1}};//一个花田上下左右四个方位;
void dfs(int x,int y)
{
    int xx,yy,i;
    a[x][y] = '@';//将该花田进行标记,防止重复搜索;
    for(i=0;i<4;i++){
        xx = x + b[i][0];
        yy = y + b[i][1];
        if(xx<0||xx>=n||yy<0||yy>=m){
            continue;//注意continue与break的区别;
        }
        if(a[xx][yy]=='#'){
            dfs(xx,yy);
        }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
 while(scanf("%d %d",&n,&m)==2){//多组输入;
    int i,j,l=0;
    memset(a,0,sizeof(a));//清空之前的数组;
    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]=='#'){
                if(a[i-1][j]=='.'||a[i+1][j]=='.'||a[i][j-1]=='.'||a[i][j+1]=='.'){
                    //对可以采的花田进行标记;
                    a[i][j] = '@';
                }
            }
        }
    }
    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;
}

猜你喜欢

转载自www.cnblogs.com/zz9100/p/11284821.html