给出一张有向图,设计一个算法判断两个点 s
与 t
之间是否存在路线。
样例
如下图:
A----->B----->C
\ |
\ |
\ |
\ v
->D----->E
样例 1:
输入:s = B and t = E,
输出:true
样例 2:
输入:s = D and t = C,
输出: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
*/
vector<int> visit;
bool hasRoute(vector<DirectedGraphNode*> graph, DirectedGraphNode* s, DirectedGraphNode* t) {
// write your code here
if(s == t)
return true;
visit.resize(graph.size(),0);
bool flag = false;
dfs(graph, s->label, t->label, flag);
return flag;
}
void dfs(vector<DirectedGraphNode*> graph, int start, int end, bool& flag)
{
if(flag == true)
return;
visit[start] = 1;
if(start == end)
{
flag = true;
return;
}
for(int i = 0; i < graph[start]->neighbors.size(); i++)
{
if(visit[graph[start]->neighbors[i]->label] == 0)
{
dfs(graph, graph[start]->neighbors[i]->label, end, flag);
}
}
}
};