题目描述:
给定一个n个点m条边的有向图,图中可能存在重边和自环。
所有边的长度都是1,点的编号为1~n。
请你求出1号点到n号点的最短距离,如果从1号点无法走到n号点,输出-1。
输入格式
第一行包含两个整数n和m。
接下来m行,每行包含两个整数a和b,表示存在一条从a走到b的长度为1的边。
输出格式
输出一个整数,表示1号点到n号点的最短距离。
数据范围
1≤n,m≤10^5
输入样例:
4 5
1 2
2 3
3 4
1 3
1 4
输出样例:
1
分析:
图的广度优先遍历的模板题。
简单描述下BFS的过程,先将最先遍历的节点入队,访问位置为true。然后出队,将相邻的还未入过队的节点均入队,访问位均置为true。当队列不空时,重复出队一个元素,即将相邻还未入队的元素入队的过程,并更新下距离数组来存储最短距离。
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 100005;
int n,m,h[maxn],e[maxn],ne[maxn],idx,d[maxn];
bool st[maxn];
queue<int> q;
void add(int a,int b){
e[idx] = b,ne[idx] = h[a],h[a] = idx++;
}
void bfs(int u){
st[u] = true;
d[u] = 0;
q.push(u);
while(q.size()){
int v = q.front();
q.pop();
for(int i = h[v];i != -1;i = ne[i]){
int w = e[i];
if(!st[w]) {
st[w] = true;
q.push(w);
d[w] = d[v] + 1;
if(w == n) return;
}
}
}
}
int main(){
cin>>n>>m;
memset(h,-1,sizeof h);
d[n] = -1;
for(int i = 0;i < m;i++){
int a,b;
cin>>a>>b;
add(a,b);
}
bfs(1);
cout<<d[n]<<endl;
return 0;
}