AcWing 847. 图中点的层次(广度优先queue)
原题链接
简单
作者:
Value
,
2020-05-26 09:08:17
,
所有人可见
,
阅读 560
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1E5 + 10;
int head[N], value[N*2], nxt[N*2];
int idx;
int n, m;
void add(int a, int b){
value[idx] = b;
nxt[idx] = head[a];
head[a] = idx ++ ;
}
void read(){
memset(head, -1, sizeof head);
cin >> n >> m;
int a, b;
while(m -- ){
scanf("%d%d", &a, &b);
add(a, b);
}
}
int dist[N];
int bfs(){
memset(dist, -1, sizeof dist);
queue<int> qu;
qu.push(1);
dist[1] = 0;
while(!qu.empty()){
int now = qu.front();
qu.pop();
for(int i = head[now]; i != -1; i = nxt[i]){
int p = value[i];
if(dist[p] == -1){
dist[p] = dist[now] + 1;
qu.push(p);
}
}
}
return dist[n];
}
int main(){
read();
cout << bfs() << endl;
return 0;
}