#include <iostream>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;
int map[1123][1123];
int vis[1123];
struct node
{
int x; /// 记录当前点
int step; /// 记录此时已走了多少步
};
void bfs(int n)
{
node a, b;
queue<node>Q;
vis[n] = 1; /// 将起点标记已经过
a.x = n;
a.step = 0;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(a.x == 1) /// 如果此时已经走到 1 则输出 此时已经走得步数 并退出
{
cout << a.step << endl;
return ;
}
for(int i = 0; i < n; i++)
{
if(map[a.x][i]&&!vis[i])
{
b.x = i; /// 记录该点
b.step = a.step + 1; /// 此时该点步数为上一点加一步
Q.push(b);
}
}
}
cout << "NO" << endl; /// 如果循环中没有return出去 则没走到 1 点
}
int main()
{
int n, m;
while(cin >> n >> m)
{
memset(map, 0, sizeof(map));
memset(vis, 0, sizeof(vis));
while(m--)
{
int u, v;
cin >> u >> v;
map[u][v] = 1;
}
bfs(n);
}
return 0;
}
图论:从起始点到目标点的最短步数(BFS)
最新推荐文章于 2018-01-03 17:50:58 发布