lintcode:Route Between Two Nodes in Graph

来源:互联网 发布:淘宝上买流量怎么退款 编辑:程序博客网 时间:2024/05/27 00:48

Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

Example

Given graph:

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

for s = B and t = E, return true

for s = D and t = C, return false


/** * Definition for Directed graph. * struct DirectedGraphNode { *     int label; *     vector<DirectedGraphNode *> neighbors; *     DirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public:    /**     * @param graph: A list of Directed graph node     * @param s: the starting Directed graph node     * @param t: the terminal Directed graph node     * @return: a boolean value     */    bool hasRoute(vector<DirectedGraphNode*> graph,                  DirectedGraphNode* s, DirectedGraphNode* t) {        // write your code here                if (s->neighbors.size() == 0)            return false;                    if (s == t)            return true;                    deque<DirectedGraphNode *> bfs;                bfs.push_back(s);                    while (bfs.size() > 0)        {            DirectedGraphNode* curNode = bfs[0];            for (int i=0; i<curNode->neighbors.size(); i++)            {                if (curNode->neighbors[i] == t)                {                    return true;                }                else                {                    bfs.push_back(curNode->neighbors[i]);                }            }                        bfs.pop_front();        }                return false;    }};


0 0
原创粉丝点击