本题我采用邻接表来存储图,由题目所有边的长度为1可以知道本题可以采用bfs来做。
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 1e5 + 9;
int e[N], ne[N], h[N], idx, n , m, d[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int bfs()
{
queue<int> q;
memset(d, -1, sizeof d);
d[1] = 0;
q.push(1);
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];//表示t能到达的点
if (d[j] == -1)
{
d[j] = d[t] + 1;
q.push(j);
}
}
}
return d[n];
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
memset(h, -1, sizeof h);//添加前初始化
cin >> n >> m;
for (int i = 1; i <= m; ++i)
{
int a, b; cin >> a >> b;
add(a, b);
}
cout << bfs();
return 0;
}
用数组来模拟邻接表,首先初始化h[]数组都为-1,表示图中没有边,e[]代表h[]所代表连接点的编号,ne[]就是指向下一个元素,d[]代表走到这个点的最短距离。要保证每个点只被走过一次,这样第一次走过这个点就是最短距离。用d[]保存是否被走过,所以初始化为-1。