(sgu-344)Weed

来源:互联网 发布:百度经纬度坐标数据库 编辑:程序博客网 时间:2024/06/06 01:14

Problem Description

Andrew has visited his garden for the last time many years ago. Today’s property taxes are so high, so Andrew decided to sell his garden. The land was not cultivated for a long time and now it is probably a lot of weed on it. Andrew wants to remove everything from the ground before selling. Now he wants to estimate the amount of work.

The garden has the rectangular form and is divided into equal squares. Andrew’s memory is phenomenal. He remembers which squares were occupied by the weed. For the purpose of simplicity, Andrew thinks that each square is either fully occupied by the weed or completely free from it. Andrew likes botany and he knows that if some square is free from the weed but at least two of its adjacent squares are occupied by the weed (two squares are adjacent if they have common side), that square will be also occupied by the weed soon. Andrew is pretty sure that during last years weed occupied every square possible. Please help Andrew to estimate how many squares is occupied by the weed.

Input
The first line of the input contains integers N and M (1 ≤ N, M ≤ 1000). Next N lines contain M characters each. Character X denotes that the corresponding square is occupied by the weed. A period character (
.) denotes an empty square.

Output
Print one integer denoting the number of squares occupied by the weed after so many years.

Example(s)
sample input
sample output
3 3 X.. .X. .X.
6

sample input
sample output
3 4 X..X .X.. .X..
12

题意:给定N,M后面是一个N*M的矩阵,’X’代表杂草,’.’代表空地,若空地的至少两个相邻位置是’X’,那么这块空地将充满杂草,问最终会有多少杂草?

分析:明显的DFS
但是写出来了,始终AC不了,找了半天,试各种不同的数据,没发现问题,然后把输入的scanf()改成cin就过了。。。 被坑了半天、、、、

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;const int N=1005;int vis[N][N],dxy[4][2]= {0,1,1,0,0,-1,-1,0};int m,n,ans;char a[N][N];void dfs(int x,int y){    int cnt=0;    if(a[x][y]=='X') return ;///剪枝    for(int i=0; i<4; i++)    {        int nx=x+dxy[i][0],ny=y+dxy[i][1];        if(nx>=0&&nx<n&&ny>=0&&ny<m&&a[nx][ny]=='X')            cnt++;    }    if(cnt>=2)///周围有两块地是'X'    {        ans++;        a[x][y]='X';        for(int i=0; i<4; i++)            dfs(x+dxy[i][0],y+dxy[i][1]);    }    else return ;}int main(){    //freopen("E:/in.txt","r",stdin);    while(~scanf("%d%d",&n,&m))    {        ans=0;        for(int i=0; i<n; i++)        {            cin>>a[i];///**不能用scanf()  !!!**            for(int j=0; j<m; j++)                if(a[i][j]=='X')                    ans++;        }        //memset(vis,0,sizeof(vis));        /*for(int i=0; i<n; i++)        {            for(int j=0; j<m; j++)                printf("%c",a[i][j]);            printf("\n");        }*/        for(int i=0; i<n; i++)            for(int j=0; j<m; j++)                if(a[i][j]=='.')                    dfs(i,j);        printf("%d\n",ans);    }    return 0;}