SSLOJ1455电子老鼠闯迷宫

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

思路

bfs例题,经过大量优化
code:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
bool a[15*15+1];
short n,i,o=1,r=1,r2,l,e;
short int q[4]={1,-1};
struct f{
 short int x;
 short int q;
} s,p2;
f b[51];
short int v[51];
void print(short int x)
{
 r=0;
 while (x!=-1)
 {
  v[++r]=b[x].x;
  x=b[x].q;
 }
 for (i=r;i>=1;i--) printf("(%d,%d)->",(v[i]-v[i]%n)/n+1,v[i]%n);
 return;
}
void bfs()
{
 while (l<r)
 {
  o++;
  r2=0;
  for (;l<r;l++)
  {
   for (v[50]=0;v[50]<4;v[50]++)
   {
    p2.x=b[l].x+q[v[50]],p2.q=l;
    if (p2.x==e)
    {
     print(l);
     printf("(%d,%d)\n%d",(p2.x-p2.x%n)/n+1,p2.x%n,o);
     return;
    }
    if (p2.x>0&&p2.x<=n*n&&!a[p2.x])
    {
     a[p2.x]=1;
     b[r2+r]=p2;
     r2++;
    }
   }
  }
  r+=r2;
 }
 return;
}
int main()
{
 scanf("%d",&n);
 scanf("%d%d",&l,&r);
 s.x=(l-1)*n+r;
 scanf("%d%d",&l,&r);
 q[2]=n,q[3]=-n,q[1]=1,q[0]=-1;
 e=(l-1)*n+r;
 for (r=1;r<=n;r++) for (l=1;l<=n;l++) scanf("%d",&a[(r-1)*n+l]);
 l=0;
 r=1;
 s.q=-1;
 b[0]=s;
 bfs();
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值