Jangalestan--一道DFS

来源:互联网 发布:淘宝空包代发 编辑:程序博客网 时间:2024/05/16 07:16

Jangalestan

题目描述

Jangalestan is a country which its map is a n*m  table. Each cell of this table is either empty or there is a tree in it. We call two cells of this table adjacent if they have an edge or vertex in common. We say there is a path between two trees in the  cells(is,js)and(if,jf) of this table if there is a sequence of the table cells such that each element of this sequence is adjacent to its previous and next elements. A city in Jangalestan is a maximal set of trees such that each pair of trees in the set has a path to each others.

You are given the map of Jangalestan. You should find the number of cities in Jangalestan.

输入

First line of Inputs contains number of the tests.

For each test case, first you are given 1<=m<=100 and 1<=n<=100  the number of rows and columns in Jangalestan’s plan. Then, in the next  m line, in each line you are given n  character. Character ‘@’ means that there is a tree in that cell and character ‘*’ shows that it’s an empty cell.

输出

For each test case output the number of cities in Jangalestan.

样例输入

2
2 3
*@*
@**
4 4
***@
@***
***@
*@@@

样例输出

1
3





#include<stdio.h>#include<string.h>char m[115][115];int v[115][115];int h,l;void dfs(int x,int y){    if(v[x][y]==1||m[x][y]=='*'||x<=0||y<=0||x>h||y>l)        return;    v[x][y]=1;    dfs(x-1,y-1);    dfs(x-1,y);    dfs(x-1,y+1);    dfs(x,y-1);    dfs(x,y+1);    dfs(x+1,y-1);    dfs(x+1,y);    dfs(x+1,y+1);}int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&h,&l);        for(int i=0;i<115;i++)        {        for(int j=0;j<115;j++)        {        m[i][j]='*';        v[i][j]=0;        }        }        int count=0;        for(int i=1; i<=h; i++)        {            //for(int j=1; j<=l; j++)            {                scanf("%s",m[i]+1);            }        }        for(int i=1; i<=h; i++)        {            for(int j=1; j<=l; j++)            {                if(m[i][j]=='@'&&v[i][j]==0)                {                    dfs(i,j);                    count++;                    //printf("%d %d\n",i,j);                }            }        }        printf("%d\n",count);    }    return 0;}
PS:虽然是改的模板,但这是第一道DFS,有意义啊!!