您的位置:首页 > 理论基础 > 数据结构算法

2139 数据结构实验之图论五:从起始点到目标点的最短步数(BFS)

2016-08-19 20:26 495 查看
数据结构实验之图论五:从起始点到目标点的最短步数(BFS)

#include <bits/stdc++.h>
using namespace std;
int vis[1110];
int map1[1100][1100];
int k,m;
struct node
{
int x,y,ans;
}q[2100];
int bfs(int x)
{
int e=0,s=0,i;
struct node t,f;
t.x=x,t.ans=0;
q[e++]=t;
vis[t.x]=1;
while(s<e)
{
t=q[s++];
if(t.x==1)
{
printf("%d\n",t.ans);
return 0 ;
}
for(i=1;i<=k;i++)
{
f.x=i;
if(vis[f.x]==0&&map1[t.x][f.x]==1)
{
f.ans=t.ans+1;
q[e++]=f;
vis[f.x]=1;
}
}
}
printf("NO\n");
return  0;
}
int main()
{
while (~scanf("%d%d",&k,&m))
{
memset (map1,0,sizeof(map1));
memset(vis,0, sizeof(vis));
while(m--)
{
int x,y;
scanf("%d%d",&x,&y);
map1[x][y]=1;
}
bfs(k);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bfs
相关文章推荐