【SSL】1455电子老鼠闯迷宫
Time Limit:1000MS
Memory Limit:65536K
Description
如下图12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路径。
Input
Output
Sample Input
12 //迷宫大小
2 9 11 8 //起点和终点
1 1 1 1 1 1 1 1 1 1 1 1 //邻接矩阵,0表示通,1表示不通
1 0 0 0 0 0 0 1 0 1 1 1
1 0 1 0 1 1 0 0 0 0 0 1
1 0 1 0 1 1 0 1 1 1 0 1
1 0 1 0 0 0 0 0 1 0 0 1
1 0 1 0 1 1 1 1 1 1 1 1
1 0 0 0 1 0 1 0 0 0 0 1
1 0 1 1 1 0 0 0 1 1 1 1
1 0 0 0 0 0 1 0 0 0 0 1
1 1 1 0 1 1 1 1 0 1 0 1
1 1 1 1 1 1 1 0 0 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
Sample Output
(2,9)->(3,9)->(3,8)->(3,7)->(4,7)->(5,7)->(5,6)->(5,5)->(5,4)->(6,4)->(7,4)->(7,3)->(7,2)->(8,2)->(9,2)->(9,3)->(9,4)->(9,5)->(9,6)->(8,6)->(8,7)->(8,8)->(9,8)->(9,9)->(10,9)->(11,9)->(11,8)
27
思路
用广搜搜索,保存路径。
代码
#include<iostream>
#include<cstdio>
using namespace std;
int n,x,y,bx,by,f[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool a[510][510],b[510][510];
struct jgt
{
int x,y,lst,s;
}c[250010];
void input()//输入
{
int i,j,t;
scanf("%d",&n);
scanf("%d%d%d%d",&x,&y,&bx,&by);
if(x==bx&&y==by)
{
printf("(%d,%d)\n1",x,y);
exit(0);
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&t);
a[i][j]=!(t);
}
return;
}
void output(int s)//输出路径
{
if(c[s].lst>=0)
output(c[s].lst);
printf("(%d,%d)->",c[s].x,c[s].y);
return;
}
void BFS()
{
int l,r,i,dx,dy;
a[x][y]=0;
c[0].x=x;
c[0].y=y;
c[0].lst=-1;
c[0].s=1;
for(l=r=0;l<=r;l++)
{
for(i=0;i<4;i++)//扩展
{
dx=c[l].x+f[i][0];
dy=c[l].y+f[i][1];
if(dx==bx&&dy==by)//到达目标
{
output(l);
printf("(%d,%d)\n%d",bx,by,c[l].s+1);
exit(0);//结束程序
}
if(1<=dx&&dx<=n&&1<=dy&&dy<=n&&a[dx][dy])
{
a[dx][dy]=0;//加入队列
c[++r].x=dx;
c[r].y=dy;
c[r].s=c[l].s+1;
c[r].lst=l;
}
}
}
return;
}
int main()
{
input();
BFS();
printf("-1");
return 0;
}