节点间通路

面试题 04.01. Route Between Nodes LCCI

来源: LeetCode 面试题 04.01. Route Between Nodes LCCI

题目描述

面试题 04.01. Route Between Nodes LCCI
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

Example1:

 Input: n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
 Output: true
Example2:

 Input: n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
 Output true
Note:

0 <= n <= 100000
All node numbers are within the range [0, n].
There might be self cycles and duplicated edges.

思路分析

就是建邻接表然后入队时候判断加入就可以

代码

class Solution {
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()
using VI = vector<int>;
using VII = vector<VI>;
using VD = vector<double>;
public:
    bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
        // bfs
        // 创建图的结构
        VI g[n];
        for(auto e:graph) g[e[0]].PB(e[1]);
        // 存储已经存储过的边
        queue<int> q;
        vector<bool>t(n,true); // 指示已经拜访过的数据
        t[start] = false;
        int cnt = n - 1;
        for(auto v:g[start]){
            if(v == target) return true;
            if(t[v]){
                q.push(v);
                t[v] = false;
            }
        }
        while(!q.empty() && cnt){
            int n = SIZE(q);
            REP(i,n){
                int x = q.front();
                q.pop(); cnt--;
                for(auto v:g[x]){
                    if(v == target) return true;
                    if(t[v]) {
                        q.push(v);
                        t[v] = false;
                    }
                }
            }
        }
        return false;
    }
};

算法分析

- 时间复杂度:O(e+v)
- 空间复杂度:O(e+v)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值