极短题干
D
e
s
c
r
i
p
t
i
o
n
Description
Description
找出一条自入口到出口最短路径。
I
n
p
u
t
Input
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
O
u
t
p
u
t
Output
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
广搜基础题
(我太菜了,改了三十分钟才改出来)。
几个注意点:
1.check函数要保证是对的。
2.for循环 0<i<4。
3.队列head和tail不要弄混。
4.方向数组不要码错
代码:
#include<iostream>
#include<cstdio>
using namespace std;
int n,cx,cy,ansy,ansx,s=0,last;
int a[1010][1010],st[1010][1010],fa[10101010];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
void print(int x)
{
if(x==0) return;
s++;
print(fa[x]);
if(x!=last)
printf("(%d,%d)->",st[x][1],st[x][2]);
else
printf("(%d,%d)\n",st[x][1],st[x][2]);
}
int check(int x,int y)
{
if(x>=1&&x<=n&&y>=1&&y<=n)
{
if(a[x][y]==0)
return true;
}
return false;
}
void bfs()
{
int head=0,tail=1;
st[1][1]=cx,st[1][2]=cy;
fa[1]=0;
a[cx][cy]=1;
while(head<=tail)
{
head++;
for(int i=0; i<4; i++)
{
if(check(st[head][1]+dx[i],st[head][2]+dy[i])==1)
{
tail++;
fa[tail]=head;
st[tail][1]=st[head][1]+dx[i];
st[tail][2]=st[head][2]+dy[i];
a[st[tail][1]][st[tail][2]]=1;
if(st[tail][1]==ansx&&st[tail][2]==ansy)
{
last=tail;
print(tail);
cout<<s<<endl;
tail=0;
return;
}
}
}
}
}
int main()
{
cin>>n;
cin>>cx>>cy>>ansx>>ansy;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
cin>>a[i][j];
bfs();
return 0;
}