SDUT 1157-小鼠迷宫问题(BFS&DFS)
2024-10-19 06:11:21
小鼠迷宫问题
Time Limit: 1500ms Memory limit: 65536K 有疑问?点这里^_^
题目描写叙述
小鼠a与小鼠b身处一个m×n的迷宫中。如图所看到的。每个方格表示迷宫中的一个房间。这m×n个房间中有一些房间是封闭的,不同意不论什么人进入。在迷宫中不论什么位置均可沿上,下。左,右4个方向进入未封闭的房间。
小鼠a位于迷宫的(p。q)方格中,它必须找出一条通向小鼠b所在的(r,s)方格的路。请帮助小鼠a找出全部通向小鼠b的最短道路。
请编程对于给定的小鼠的迷宫,计算小鼠a通向小鼠b的全部最短道路。
输入
本题有多组输入数据,你必须处理到EOF为止。
每组数据的第一行有3个正整数n,m。k,分别表示迷宫的行数,列数和封闭的房间数。
接下来的k行中。每行2个正整数。表示被封闭的房间所在的行号和列号。
最后的2行。每行也有2个正整数,分别表示小鼠a所处的方格(p,q)和小鼠b所处的方格(r,s)。
每组数据的第一行有3个正整数n,m。k,分别表示迷宫的行数,列数和封闭的房间数。
接下来的k行中。每行2个正整数。表示被封闭的房间所在的行号和列号。
最后的2行。每行也有2个正整数,分别表示小鼠a所处的方格(p,q)和小鼠b所处的方格(r,s)。
输出
对于每组数据,将计算出的小鼠a通向小鼠b的最短路长度和有多少条不同的最短路输出。
每组数据输出两行,第一行是最短路长度;第2行是不同的最短路数。
每组输出之间没有空行。
每组数据输出两行,第一行是最短路长度;第2行是不同的最短路数。
每组输出之间没有空行。
假设小鼠a无法通向小鼠b则输出“No Solution!”。
演示样例输入
8 8 3
3 3
4 5
6 6
2 1
7 7
演示样例输出
11
96
BFS搜到最短路径。 。然后BFS怒搜路径数
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <set>
#include <map>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#define LL long long
using namespace std;
const int INF = 0x3f3f3f3f;
struct node
{
int x,y,step;
};
int sb,ans,n,m,sx,sy,ex,ey,dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool ma[110][110],vis[110][110];
int bfs()
{
memset(vis,0,sizeof(vis));
queue <node> Q;
node now,next;
now.x=sx;now.y=sy;now.step=0;
vis[sx][sy]=1;
Q.push(now);
while(!Q.empty())
{
now=Q.front();Q.pop();
if(now.x==ex&&now.y==ey)
return now.step;
for(int i=0;i<4;i++)
{
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
if(next.x>=1&&next.x<=n&&next.y>=1&&next.y<=m&&!vis[next.x][next.y]&&ma[next.x][next.y])
{
vis[next.x][next.y]=1;
next.step=now.step+1;
Q.push(next);
}
}
}
return -1;
}
void dfs(int x,int y,int step)
{
if(step>sb) return ;
if(x==ex&&y==ey&&step==sb)
{
++ans;
return ;
}
for(int i=0;i<4;i++)
{
int tx=x+dir[i][0];
int ty=y+dir[i][1];
if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&!vis[tx][ty]&&ma[tx][ty])
{
vis[tx][ty]=1;
dfs(tx,ty,step+1);
vis[tx][ty]=0;
}
}
}
int main()
{
int k,u,v;
while(~scanf("%d%d%d",&n,&m,&k))
{
memset(ma,1,sizeof(ma));
while(k--)
{
scanf("%d%d",&u,&v);
ma[u][v]=0;
}
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
sb=bfs();
if(sb==-1)
{
puts("No Solution!");
continue;
}
printf("%d\n",sb);
memset(vis,0,sizeof(vis));
ans=0;vis[sx][sy]=1;
dfs(sx,sy,0);
printf("%d\n",ans);
}
return 0;
}
最新文章
- 总结-javascript
- try,catch,finally含return时的执行顺序及丢失的伪例
- ionic入门之色彩、图标、边距和界面组件:列表
- ICSharpCode.SharpZipLib简单使用
- 【iCore3 双核心板】例程三十一:HTTP_IAP_FPGA实验——更新升级FPGA
- C#微信公众号开发-MVC模式公共类封装
- Qt webkit插件相关知识
- win2003 多域名绑定一个ip
- WSGI、flup、fastcgi、web.py的关系
- opencv保存选择图像中的区域(二)
- .net中下载文件的方法(转)
- Missing Ranges 解答
- struts2+hibernate环境搭建
- C#钩子类 几乎捕获键盘鼠标所有事件
- Python内置函数(14)——bytes
- 微信小程序-参数传递与事件处理
- storm 001
- CentOS 7 安装pip2
- Django入门与实践-第12章:复用模板(完结)
- [置顶] Spring中自定义属性编辑器