题目
节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
示例1:
输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
输出:true
解题思路
DFS
代码
class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
// 邻接表,方便查找可到达的相邻节点
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int[] path : graph) {
if (!map.containsKey(path[0])) map.put(path[0], new HashSet<>());
map.get(path[0]).add(path[1]);
}
// 深度优先
return dfs(start, target, map, new HashSet<>());
}
private boolean dfs(int start, int target, Map<Integer, Set<Integer>> map, Set<Integer> visited) {
// 重复访问到相同节点,说明有环,返回false
if (visited.contains(start) || !map.containsKey(start)) return false;
// 达到终点,返回true
else if (map.get(start).contains(target)) return true;
visited.add(start);
// 继续访问相邻接点
for (int i : map.get(start)) if (dfs(i, target, map, visited)) return true;
return false;
}
}