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;
}