lintcode-图中两个点之间的路线-176

给出一张有向图,设计一个算法判断两个点 s t 之间是否存在路线。

如下图

A----->B----->C
 \     |
  \    |
   \   |
    \  v
     ->D----->E

for s = B and t = E, return true

for s = D and t = C, return false


第一种解法 DFS

/**
 * Definition for Directed graph.
 * struct DirectedGraphNode {
 *     int label;
 *     vector<DirectedGraphNode *> neighbors;
 *     DirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    
    map<DirectedGraphNode*,bool> vis;
   
    bool dfs(DirectedGraphNode* s,DirectedGraphNode* t){
        if(s==t)
            return true;
    
        for(auto e:s->neighbors){
            if(vis[e])
                continue;
            vis[e]=true;    
            if(dfs(e,t))
                return true;
        }
        return false;
    }
    bool hasRoute(vector<DirectedGraphNode*> graph,
                  DirectedGraphNode* s, DirectedGraphNode* t) {
        if(graph.empty())
            return false;
        return dfs(s,t);
    }
};

第二种解法 BFS

/**
 * Definition for Directed graph.
 * struct DirectedGraphNode {
 *     int label;
 *     vector<DirectedGraphNode *> neighbors;
 *     DirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
  
    bool hasRoute(vector<DirectedGraphNode*> graph,
                  DirectedGraphNode* s, DirectedGraphNode* t) {
        
        queue<DirectedGraphNode*> que;
        map<DirectedGraphNode*,bool>  vis;
        que.push(s);
        vis[s]=true;
        while(!que.empty()){
            int len=que.size();
            while(len--){
                DirectedGraphNode* cur=que.front();
                if(cur==t)
                    return true;
                que.pop();
                for(auto e:cur->neighbors){
                    if(vis[e])
                        continue;
                    que.push(e);    
                    vis[e]=true;    
                }
            }
        }
        return false;
    }
};



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值