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;
}
};