思路:
(1)邻接表建图,注意是有向图。
(2)bfs()查询最短路,注意区分idx与图本身编号。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int h[N],e[N*2],ne[N*2],idx,d[N];
int n,m;
void add(int a,int b)
{
e[idx] = b;ne[idx] = h[a],h[a] = idx ++;
}
void bfs()
{
queue<int> q;
q.push(1);
memset(d,-1,sizeof d);
d[1] = 0;
while(!q.empty())
{
int x = q.front();
q.pop();
for(int i = h[x];i != -1;i = ne[i])
{
int j = e[i];
if(d[j] == -1)
{
d[j] = d[x] + 1;
q.push(j);
}
}
}
cout << d[n] << endl;
}
int main()
{
cin >> n>> m;
memset(h,-1,sizeof h);
while(m --)
{
int a,b;
cin >> a >> b;
add(a,b);
}
bfs();
return 0;
}