版权声明:本文为博主原创文章,未经博主允许可以转载。(转呀转呀/笑哭),希望标注出处hhh https://blog.csdn.net/qq_36428171/article/details/89361521
题目:
给定有向图的边 edges,以及该图的始点 source 和目标终点 destination,确定从始点 source 出发的所有路径是否最终结束于目标终点 destination,即:
- 从始点 source 到目标终点 destination 存在至少一条路径
- 如果存在从始点 source 到没有出边的节点的路径,则该节点就是路径终点。
- 从始点source到目标终点 destination 可能路径数是有限数字
当从始点 source 出发的所有路径都可以到达目标终点 destination 时返回 true,否则返回 false。
题目链接:从始点到终点的所有路径
C++:
class Solution {
public:
bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>> graph(n);
bool vis[n];
memset(vis, 0, sizeof(vis));
for(int i = 0; i < edges.size(); i++){
graph[edges[i][0]].push_back(edges[i][1]);
}
if(graph[destination].size() != 0)
return false;
if(n == 1)
return true;
vis[source] = true;
if(!dfs(graph, vis, source, destination))
return false;
return true;
}
bool dfs(vector<vector<int>> &graph, bool *vis, int last, int destination){
if(graph[last].size() == 0)
return false;
for(int i = 0; i < graph[last].size(); i++){
if(vis[graph[last][i]])
return false;
else{
if(graph[last][i] == destination){
continue;
}
vis[graph[last][i]] = true;
if(!dfs(graph, vis, graph[last][i], destination))
return false;
vis[graph[last][i]] = false;
}
}
return true;
}
};