典型的bfs最短路搜索

框架

void bfs()
{
    q.push(起点);
    
    while(队列不空)
    {
        auto t = 队首元素;
        for(所有相邻节点)
        {
            如果可以扩展,就扩展,入队;
        }
    }
}

代码

//bfs
#include<bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

int n, m;
int h[N], e[N], ne[N], idx = 0;

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int d[N];
int bfs()
{
    queue<int> q;
    q.push(1);
    memset(d, -1, sizeof d);
    d[1] = 0;

    while(q.size())
    {
        auto t = q.front();q.pop();

        for(int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if(d[j] == -1)
            {
                d[j] = d[t] + 1;
                q.push(j);
            }
        }
    }
    return d[n];
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for(int i = 0; i < m ;i++)
    {
        int a, b;
        cin >> a >> b;
        add(a, b);
    }

    cout << bfs() << endl;
    return 0;
}