Route Between Two Nodes in Graph
题目:
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
分析:
一道简单的bfs题目,注意lintcode上面给出的vector of DirectedGraphNode*本身就是个adj list,不需要再进行转化,直接开queue做就可以。
解法:
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 == t) {
return true;
}
if (s == NULL || t == NULL || graph.size() == 0) {
return false;
}
bool res = false;
queue<DirectedGraphNode*> Q;
Q.push(s);
while (!Q.empty() ) {
DirectedGraphNode* temp = Q.front();
Q.pop();
for (int i = 0; i < temp->neighbors.size(); i++) {
if (temp->neighbors[i] == t) {
res = true;
break;
}
Q.push(temp->neighbors[i]);
}
}
return res;
}
};