题目描述:
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
这题我发现只能用bfs做,dfs做会超时(坑爹呀!)。bfs用简单的传统算法就好了。
Mycode(AC = 396ms):
/**
* 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
stack<DirectedGraphNode *> sgraph;
sgraph.push(s);
// bfs to search the neighbors
while (!sgraph.empty()) {
DirectedGraphNode *node = sgraph.top();
sgraph.pop();
if (node->label == t->label) return true;
for (int i = 0; i < node->neighbors.size(); i++) {
sgraph.push(node->neighbors[i]);
}
}
return false;
}
};
本文介绍了一种使用广度优先搜索(BFS)算法来判断有向图中两个节点间是否存在路径的方法,并提供了一个具体的代码实现案例。
1453

被折叠的 条评论
为什么被折叠?



