1. 题目
给定有向图的边 edges,以及该图的始点 source 和目标终点 destination,确定从始点 source 出发的所有路径是否最终结束于目标终点 destination,即:
从始点 source 到目标终点 destination 存在至少一条路径
如果存在从始点 source 到没有出边的节点的路径,则该节点就是路径终点。
从始点source到目标终点 destination 可能路径数是有限数字
当从始点 source 出发的所有路径都可以到达目标终点 destination 时返回 true,否则返回 false。
输入:n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
输出:false
说明:节点 1 和节点 2 都可以到达,但也会卡在那里。
输入:n = 4, edges = [[0,1],[0,3],[1,2],[2,1]], source = 0, destination = 3
输出:false
说明:有两种可能:在节点 3 处结束,或是在节点 1 和节点 2 之间无限循环。
输入:n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
输出:true
/*
* @Author: Zhibo Wang
* @Date: 2021-05-07 21:51:13
* @LastEditTime: 2021-05-07 22:08:59
*/
#include<bits/stdc++.h>
class Solution{
public:
bool leadToDestination(int n,std::vector<std::vector<int>>& edge,int start,int end){
std::vector<std::vector<int>> m(m);
std::vector<bool> visited(n,false);
for(auto e:edge){
m[e[0]].push_back(e[1]);
}
if(!m[end].empty()){
return false;
}
return DFS(m,visited,start,end);
}
bool DFS(std::vector<std::vector<int>>& m,std::vector<bool>& visitd,int cur,int end){
if(!m[cur].size()==0&&cur!=end){
return false;
}
for(auto next:m[cur]){
if(visitd[next]){
return false;
}
visitd[next]=true;
if(!DFS(m,visitd,cur,end)){
return false;
}
visitd[next]=false;
}
}
};