[数组模拟] AcWing 847. 图中点的层次

输入样例:

4 5
1 2
2 3
3 4
1 3
1 4

输出样例:

1

思路:

所有边的长度都是 1, 权值相同求有向图最短路, 广度优先即可

,因为要求的是1~n的距离, 我们另设一个数组d[i] 来表示1~i之间的距离

有关边的添加思路可以参考数组实现单双链表的快速操作[时间复杂度为O(1)]_☆迷茫狗子的秘密基地☆-CSDN博客icon-default.png?t=L9C2https://blog.csdn.net/qq_39391544/article/details/120680300

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1e5+10;
int n, m;
int h[N], e[N], ne[N], idx;
int d[N]; //距离

void add(int a, int b){
    e[idx]=b, ne[idx]=h[a], h[a]=idx++;
}
int bfs()
{
    int q[N];
    int front = 0, rear = 0;
    q[0] = 1;
    
    memset(d, -1, sizeof d);
    d[1] = 0;
    while(front <= rear)
    {
        int t = q[front++];
        
        for(int i = h[t]; i != -1; i = ne[i]){
            int j = e[i];
            if(d[j]==-1){
                d[j] = d[t]+1;
                q[++rear] = j;
            }
        }
    }
    return d[n];
}
int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    
    int a, b;
    for(int i = 0; i < m; i ++){
        cin >> a >> b;
        add(a, b);
    }
    cout << bfs();
    return 0;
}

原文地址:https://www.cnblogs.com/Knight02/p/15799056.html