Jangalestan--一道DFS

这道题目描述了Jangalestan国家的地图,由一个n*m的表格构成,表格中每个单元格可能是空的或是有树木。如果两个单元格共享边或顶点,则认为它们相邻。两个树木之间存在路径,当存在一系列单元格,且相邻单元格之间有路径连接。城市是指森林中任意两棵树都存在路径连接的最大集合。输入包括测试用例数、地图的行数和列数,以及地图的具体表示。输出是Jangalestan的森林城市数量。提供的样例输入和输出未给出具体数据。
摘要由CSDN通过智能技术生成

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,有意义啊!!





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值