C++ 代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<string>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e5 + 5;
int head[maxn],Next[maxn],ver[maxn],edge[maxn];
int dist[maxn],vis[maxn];
int n,m,tot;
int main(void) {
void add(int x,int y,int w);
void spfa();
memset(dist,0x3f,sizeof(dist));
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&m);
int x,y;
for(int i = 1; i <= m; i ++) {
scanf("%d%d",&x,&y);
add(x,y,1);
}
spfa();
if(dist[n] == INF) cout<<-1<<endl;
else cout<<dist[n]<<endl;
return 0;
}
void add(int x,int y,int w) {
ver[++tot] = y,edge[tot] = w;
Next[tot] = head[x],head[x] = tot;
return ;
}
void spfa() {
queue<int>q;
dist[1] = 0;
q.push(1),vis[1] = 1;
while(!q.empty()) {
int x = q.front();
q.pop();
vis[x] = 0;
for(int i = head[x]; i ; i = Next[i]) {
int y = ver[i],z = edge[i];
if(dist[y] > dist[x] + z) {
dist[y] = dist[x] + z;
if(vis[y] == 0) {
q.push(y);
vis[y] = 1;
}
}
}
}
return;
}