Acwing 847. 图中点的层次(树与图的BFS)
给定一个n个点m条边的有向图,图中可能存在重边和自环。
所有边的长度都是1,点的编号为1~n。
请你求出1号点到n号点的最短距离,如果从1号点无法走到n号点,输出-1。
输入格式
第一行包含两个整数n和m。
接下来m行,每行包含两个整数a和b,表示存在一条从a走到b的长度为1的边。
输出格式
输出一个整数,表示1号点到n号点的最短距离。
数据范围
1≤n,m≤105
输入样例:
4 5
1 2
2 3
3 4
1 3
1 4
输出样例:
1
题解(STL版)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1000010;
int e[N], ne[N], idx, h[N];
int n, m;
queue<int> q;
int dist[N];
//add函数是存指针数组h[k]中,以k为根节点的所有子节点的元素链表
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int bfs(){
memset(dist, -1, sizeof dist);//因为题目说没找到要输出-1
dist[1] = 0;//到数值为1的路径是0
q.push(1);
while (q.size()){
int t = q.front();
q.pop();
//遍历所有以数值t为根节点的所有子节点
for (int i = h[t] ; i != -1 ; i = ne[i]){
int j = e[i];
if (dist[j] == -1){
dist[j] = dist[t] + 1;
q.push(j);
}
}
}
return dist[n];
}
int main(){
cin >> n >> m;
memset(h, -1, sizeof h);
while(m -- ){
int a, b;
cin >> a >> b;
add(a, b);
}
cout << bfs() << endl;
return 0;
}
- “add函数是存指针数组h[k]中,以k为根节点的所有子节点的元素链表”,这句话值得细品,妙妙妙!!!
- 注意:我们每次push进去的都是一个value,而不是一个idx,而链表在遍历的过程中,也就是for循环中,得到的i都是idx!!!
题解(数组模拟队列版)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 100010;
int n, m;
int e[N], ne[N], h[N], idx;
int d[N], q[N];
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int bfs(){
memset(d, -1, sizeof d);
int hh = 0, tt = 0;
d[1] = 0;
q[0] = 1;
while(hh <= tt){
int t = q[hh ++ ];
for (int i = h[t]; i != -1 ; i = ne[i]){
int j = e[i];
if (d[j] == -1){
d[j] = d[t] + 1;
q[ ++ tt ] = j;
}
}
}
return d[n];
}
int main(){
memset(h, -1, sizeof h);
cin >> n >> m;
while(m -- ){
int a, b;
cin >> a >> b;
add(a, b);
}
cout << bfs() << endl;
return 0;
}