节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
示例1:
输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
输出:true
示例2:
输入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
输出 true
提示:
节点数量n在[0, 1e5]范围内。
节点编号大于等于 0 小于 n。
图中可能存在自环和平行边。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/route-between-nodes-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
图结构小白的 dfs 说明:
因为题目说是有向图,因此利用哈希表构建链式图,key 为 graph 数组的第一位,并将 value 设置为集合(主要是存在一些冗余数据,可以用这种笨办法构建)。如果 key 已经被构建,则直接往 value 中添加可以通向的节点即可。
dfs 中,不断向下搜索,变换 start 的值,也就是依据图来往下遍历。如果该节点(start)能够通向 target,即成功,返回 true,否则返回 false。
具体代码如下:
class Solution {
public static boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>(); // 存储有向图的哈希表
for( int i = 0; i < graph.length; i++) {
if( map.containsKey(graph[i][0]) ) { // 如果该节点已经被构建,则直接在集合中添加
map.get(graph[i][0]).add(graph[i][1]);
} else {
Set<Integer> temp = new HashSet<Integer>();
temp.add(graph[i][1]); // 存储可以通向的节点
map.put(graph[i][0], temp); // 构建节点
}
}
return dfs(map, start, target);
}
private static boolean dfs(Map<Integer, Set<Integer>> map, int start, int target) {
if( map.get(start) == null ) return false; // 如果该 key 没有任何方向节点,则表示走不通,返回 false
if( map.get(start).contains(target) ) { // 如果该节点可以通向 target,即在集合中有对应的 target,则返回 true
return true;
}
for( Integer x : map.get(start) ) { // 遍历该节点能够通向的所有节点
if( dfs(map, x, target) ) { // 如果能够到达 target,则返回true
return true;
}
}
return false; // 如果所有节点都走了一遍,但是不能通向 target,则返回 false
}
}