hdu~1312(dfs)

本文介绍了一道简单的深度优先搜索(DFS)题目,通过C语言实现,目标是从指定起点出发,计算可达点的数量。使用递归方式遍历地图上的每个位置,并标记已访问区域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一道简单的dfs

http://acm.hdu.edu.cn/showproblem.php?pid=1312

@为起点,#为墙,'.'为路,问你能到达的点有几个。


#include <stdio.h>
#include <string.h>

int n,m,max;
int sx,sy;
int dirx[5]={0,0,1,0,-1},diry[5]={0,1,0,-1,0};
char s[25][25];

void dfs(int x,int y)
{
    if(x<1 || x>n || y<1 || y>m)
        return ;
    if(s[x][y]=='#')
        return ;
    max++;<span style="white-space:pre">				</span>//每到一个点,max++
    for(int i=1;i<=4;i++)
    {
        int tx=x+dirx[i];
        int ty=y+diry[i];
        s[x][y]='#';<span style="white-space:pre">		</span>//走过直接标记为墙,因为以后不用重新走过了
        dfs(tx,ty);
    }
}
int main()
{
    int i,j;
    while(scanf("%d %d",&m,&n) && (n!=0 || m!=0))
    {
        max=0;
        for(i=1;i<=n;i++)
        {
            scanf("%s",&s[i][1]);
            for(j=1;j<=m;j++)
                if(s[i][j]=='@')<span style="white-space:pre">	</span>//记录起点
                    sx=i,sy=j;
        }
        dfs(sx,sy);
        printf("%d\n",max);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值