#include <bits/stdc++.h>
using namespace std;
int n, m;
bool vis[1010];
int Graph[1010][1010];
void BFS();
struct node
{
int _end;
int step;
};
int main()
{
int u, v;
while(cin >> n >> m)
{
memset(Graph, 0, sizeof(Graph));
memset(vis, 0, sizeof(vis));
for(int i = 0; i < m; i++)
{
cin >> u >> v;
Graph[u][v] = 1;
}
BFS();
}
return 0;
}
void BFS()
{
queue<node *>Q;
node *tmp = new node;
tmp -> _end = n;
tmp -> step = 0;
Q.push(tmp);
vis[n] = 1;
while(!Q.empty())
{
node *now = Q.front();
Q.pop();
if(now -> _end == 1)
{
cout << now -> step << endl;
return;
}
for(int i = n; i >= 1; i--)
{
if(!vis[i] && Graph[now -> _end][i])
{
vis[i] = 1;
node *tmp = new node;
tmp->_end = i;
tmp->step = now->step+1;
Q.push(tmp);
}
}
}
cout << "NO" << endl;
}
SDUT 2139 图结构练习——BFS——从起始点到目标点的最短步数
最新推荐文章于 2020-08-19 20:55:17 发布