有向路径检查

对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。

给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。

-------------------------

思路:实质实现图的广度优先遍历(BFS),关键记录被访问的节点,以下给出两种方法

一种不用记录,一种借助map。


/*
struct UndirectedGraphNode {
    int label;
    vector<struct UndirectedGraphNode *> neighbors;
    UndirectedGraphNode(int x) : label(x) {}
};*/
 
class Path {
public:
    bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) {
        // write code here
        if (!a || !b)
            return false;
        return checkSingle(a, b) || checkSingle(b, a);
    }
private:
    bool checkSingle(UndirectedGraphNode* a, UndirectedGraphNode* b){
        queue<struct UndirectedGraphNode *> que;//BFS工作队列
        que.push(a);
        while (!que.empty()){
            //直到队空
            UndirectedGraphNode* t = que.front();
            que.pop();//出队
            if (t == b)
                return true;
            //t的所有邻接点进队,晴空邻接点
            vector<struct UndirectedGraphNode *>::iterator it;
            for (it = t->neighbors.begin(); it!=t->neighbors.end(); ++it){
                //入队
                que.push(*it);
            }
            t->neighbors.clear();
        }
        return false;
    }
};
-----------------------------

以下使用map记录访问标记:

/*
struct UndirectedGraphNode {
    int label;
    vector<struct UndirectedGraphNode *> neighbors;
    UndirectedGraphNode(int x) : label(x) {}
};*/
class Path {
public:
    bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) {
        // write code here
        if (!a || !b)
            return false;
        return checkSingle(a, b) || checkSingle(b, a);
    }
private:
    bool checkSingle(UndirectedGraphNode* a, UndirectedGraphNode* b){
        queue<struct UndirectedGraphNode *> que;
        map<UndirectedGraphNode*,bool> visited;
        que.push(a);
        while (!que.empty()){
            UndirectedGraphNode* cur = que.front();
            que.pop();
            if (cur == b)
                return true;
            visited[cur] = true;
            //邻接点进队
            vector<struct UndirectedGraphNode *>::iterator it;
            for (it = cur->neighbors.begin(); it!=cur->neighbors.end(); ++it){
                //若未访问过入队
                if (!visited[*it])
                    que.push(*it);
            }
        }
        return false;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值