FZU 1205(小鼠迷宫问题)BFS+DFS的基本综合运用(同一题目中体现两种搜索方法的特点)

看一大牛的文章发现了关于BFS和DFS的演示:感觉挺好!
 广度优先遍历演示地址:

图的深度优先遍历演示系统:
 
关于fzu 1025 题目地址: http://acm.fzu.edu.cn/problem.php?pid=1205
题目大意:在一个迷宫内输出位置a到位置b的最短距离,以及一共有多少种不同的最短路径数。
分析:利用bfs可以计算出最短路径的距离len(即移动次数),然后用dfs计算出等于len(移动次数)时有多少种不同的最短路径。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
#define N 100
int mark[N][N];
int map[N][N];
struct node{
	int x,y,step;
};
int n,m,k;
int min_step;
int num;
int x1,y1,x2,y2;
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int BFS()
{
	int x,y,i;
	queue<node>q;
	node cur,next;
	cur.x=x1;cur.y=y1;cur.step=0;
	q.push(cur);
	mark[x1][y1]=1;
	while(!q.empty())
	{
		cur=q.front();
		q.pop();
		if(cur.x==x2&&cur.y==y2)
		{
			return cur.step;
		}
	    for(i=0;i<4;i++)
		{
			next.x=x=cur.x+dir[i][0];
			next.y=y=cur.y+dir[i][1];
			if(x>=1&&x<=n&&y>=1&&y<=m&&mark[x][y]==0)
			{
				next.step=cur.step+1;
				q.push(next);
				mark[x][y]=1;
			}
		}
	}
	return -1;
}
void DFS(int x,int y,int c_step)
{
	if(x==x2&&y==y2&&c_step==min_step)
	{
		num++; return ;
	}
	if((x>x2?x-x2:x2-x)+(y>y2?y-y2:y2-y)+c_step>min_step) return ;
	int i;
	for(i=0;i<4;i++)
	{
		int xx,yy;
		xx=x+dir[i][0];
		yy=y+dir[i][1];
		if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&map[xx][yy]==0)
		{
			map[xx][yy]=1;
			DFS(xx,yy,c_step+1);
			map[xx][yy]=0;
		}
	}

}
int main()
{
	
	while(scanf("%d%d%d",&n,&m,&k)!=EOF){
	int i;
	memset(mark,0,sizeof(mark));
	memset(map,0,sizeof(map));
	for(i=1;i<=k;i++)
	{
		int a,b;
		cin>>a>>b;
		map[a][b]=1;
		mark[a][b]=1;
	}
	cin>>x1>>y1;
	cin>>x2>>y2;
	min_step=-1;
	min_step=BFS();


	//cout<<min_step<<endl;
	if(min_step==-1)
		cout<<"No Solution!"<<endl;
	else
	{
		num=0;
		DFS(x1,y1,0);
		cout<<min_step<<endl;
	    cout<<num<<endl;       }

	}
	
	return 0;
}







http://sjjg.js.zwu.edu.cn/SFXX/sf1/sfys.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值