Acwing 847. 图中点的层次(树与图的BFS)

Acwing 847. 图中点的层次(树与图的BFS)

给定一个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

题解(STL版)

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

using namespace std;

const int N = 1000010;

int e[N], ne[N], idx, h[N];
int n, m;
queue<int> q;
int dist[N];

//add函数是存指针数组h[k]中,以k为根节点的所有子节点的元素链表
void add(int a, int b){
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}


int bfs(){
    memset(dist, -1, sizeof dist);//因为题目说没找到要输出-1
    dist[1] = 0;//到数值为1的路径是0
    q.push(1);
    
    while (q.size()){
        int t = q.front();
        q.pop();
        
        //遍历所有以数值t为根节点的所有子节点
        for (int i = h[t] ; i != -1 ; i = ne[i]){
            int j = e[i];
            if (dist[j] == -1){
                dist[j] = dist[t] + 1;
                q.push(j);
            }
        }
    }
    
    return dist[n];
    
}


int main(){
    cin >> n >> m;
    
    memset(h, -1, sizeof h);
    
    while(m -- ){
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
    
    cout << bfs() << endl;
    
    return 0;
}
  • “add函数是存指针数组h[k]中,以k为根节点的所有子节点的元素链表”,这句话值得细品,妙妙妙!!!
  • 注意:我们每次push进去的都是一个value,而不是一个idx,而链表在遍历的过程中,也就是for循环中,得到的i都是idx!!!

题解(数组模拟队列版)

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

using namespace std;

const int N = 100010;

int n, m;
int e[N], ne[N], h[N], idx;
int d[N], q[N];


void add(int a, int b){
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}

int bfs(){
    
    memset(d, -1, sizeof d);
    
    int hh = 0, tt = 0;
    d[1] = 0;
    
    q[0] = 1;
    while(hh <= tt){
        int t = q[hh ++ ];
        for (int i = h[t]; i != -1 ; i = ne[i]){
            int j = e[i];
            if (d[j] == -1){
                d[j] = d[t] + 1;
                q[ ++ tt ] = j;
            }
        }
    }
    
    return d[n];
}


int main(){
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while(m -- ){
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
    
    cout << bfs() << endl;
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值