题目: AcWing 847. 图中点的层次
给定一个 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
分析:
树与图的广度优先遍历与普通的遍历无差异,只是在搜索周围一圈的时候使用邻接表进行查找
#include <iostream>
#include <map>
#include <vector>
#include <queue>
using namespace std;
typedef pair<int,int> PII;
map<int,vector<int>> list;
queue<PII> q;
const int N = 100010;
int st[N];
int n,m;
int main()
{
cin>>n>>m;
while(m--)// 建图
{
int a,b;
cin>>a>>b;
list[a].push_back(b);
}
q.push({1,0});
while(!q.empty())
{
PII s=q.front();
if(s.first==n)// 如果找到
{
cout<<s.second<<endl;
return 0;
}
st[s.first]=true;
for(auto it:list[s.first])
{
if(st[it])continue;
q.push({it,s.second+1});
}
q.pop();
}
cout<<"-1"<<endl;
return 0;
}