您的位置:首页 > 其它

图结构练习——BFS——从起始点到目标点的最短步数

2016-08-18 08:44 316 查看
借助结构体队列遍历。

题目链接

#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

const int maxn=100000+100;

typedef struct
{
int num;
int y;
}que;

que q[maxn];
bool flag[maxn];
bool mp[1000][1000];

void bfs(int x)
{
memset(flag, 0, sizeof(flag));
que t, k;
t.y=x;
t.num=0;
int n=0, s=0;
q[n++]=t;
while(s<n)
{
t=q[s++];
if(t.y==1)
{
cout<<t.num<<endl;
return;
}
for(int i=1;i<=x;i++)
{
k.y=i;
if(!flag[k.y]&&mp[t.y][k.y])
{
flag[k.y]=1;
k.num=t.num+1;
q[n++]=k;
}
}
}
cout<<"NO"<<endl;
return;
}

int main()
{
ios::sync_with_stdio(false);
int n, m;
while(cin>>n>>m)
{
int x, y;
memset(mp, 0, sizeof(mp));
for(int i=0;i<m;i++)
{
cin>>x>>y;
mp[x][y]=1;
}
bfs(n);
}
return 0;
}


补一个最近刚写的

#include <iostream>
#include <algorithm>
#include <string>
#include <queue>

using namespace std;

typedef struct point
{
int num;
int x;
}point;

const int maxn = 1001;

bool mp[maxn][maxn];
bool vis[maxn+maxn];
int n, m;

queue <point> que;

void init()
{
while(!que.empty())
que.pop();
for(int i=1; i<=n; ++i)
for(int j=1; j<=n; ++j)
mp[i][j] = false;
for(int i=1;i<=n;++i)
vis[i] = false;
}

void bfs(int s)
{
vis[s] = true;
point ss;
ss.x = s;
ss.num = 0;
que.push(ss);
while(!que.empty())
{
point now = que.front();
que.pop();
if(now.x == 1)
{
cout<<now.num<<endl;
return;
}
for(int i=1; i<=n; ++i)
{
point temp;
if(mp[now.x][i] && !vis[i])
{
temp.x = i;
temp.num = now.num+1;
vis[i] = true;
que.push(temp);
}
}
}
cout<<"NO"<<endl;
}

int main()
{
ios::sync_with_stdio(false);
while(cin>>n>>m)
{
init();
for(int i=0;i<m;++i)
{
int a, b;
cin>>a>>b;
mp[a][b] = true;
}
bfs(n);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐