poj 1979 zoj 2165 Red and Black 深搜做法

本文介绍了一个简单的深搜算法实现案例,通过递归的方式遍历所有可达节点,并统计可达节点的数量。文章展示了完整的代码实现,包括如何定义方向数组来控制搜索的方向,如何判断当前位置是否在地图范围内,以及如何进行深度优先搜索。

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

/* 第一个深搜 参考了大牛的代码 并作了少许优化 */ #define LOCAL #include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<cstdlib> #include<cctype> #include<iomanip> #include<string> #include<algorithm> #include<ctime> #include<stack> #include<queue> #include<vector> #define N 25 using namespace std; int m,n,ans,rec[N][N],dir[4][2]={0,1,0,-1,1,0,-1,0}; //控制转向 bool legal(int x,int y) //判断数据是否合法 {if(x>=1&&x<=m&&y>=1&&y<=n) return true;return false;} void DFS(int x,int y) //递归搜索 { int i,sx,sy; rec[x][y]=1;ans++;//标记当前点已经遍历过,每遍历一个节点ans+1 for(i=0;i<4;i++) { sx=x+dir[i][0];sy=y+dir[i][1];//转向 if(!rec[sx][sy]&&legal(sx,sy)) //若当前结点未被遍历且”合法“遍历该节点 DFS(sx,sy); } } int main() { #ifdef LOCAL freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int i,j,x,y;char ch; while(cin>>n>>m&&m&&n) { memset(rec,0,sizeof(rec)); for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { cin>>ch; if(ch=='#') rec[i][j]=1; else if(ch=='@') {x=i;y=j;} } } ans=0; DFS(x,y); cout<<ans<<endl; } return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值