https://leetcode-cn.com/problems/route-between-nodes-lcci/
题目:面试题 04.01. 节点间通路
节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
输出:true输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
输出:true
参考资料:https://leetcode-cn.com/problems/route-between-nodes-lcci/solution/javalin-jie-biao-yan-du-bian-li-by-wonderzlf/
直接看这个就行 很详细
首先先转为邻接表,然后广度搜索遍历,见代码注释
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
// 转为邻接表 adj是一个数组,每个数组元素类型都是ArrayList
ArrayList[] adj = new ArrayList[n]; // n个结点 邻接表就有n行
for (int[] ints : graph) {
int from = ints[0];
int to = ints[1];
if (adj[from] == null) {
adj[from] = new ArrayList();
}
adj[from].add(to);
}
// System.out.println(adj[0].getClass()); // class java.util.ArrayList
// for (int i = 0; i < adj.length; i++) {
// System.out.println(i + ":" + adj[i]);
// }
return hasPath(n,adj,start,target);
}
public boolean hasPath(int n, ArrayList<Integer>[] adj, int start, int target){
LinkedList<Integer> queue = new LinkedList<>(); // 队列,记录start能够到达的结点
boolean[] visited = new boolean[n]; // 标记这n个结点是否被访问
queue.offer(start); // 将start加入到队列
visited[start] = true;// 标记start为已访问,也就是已入队
while (!queue.isEmpty()){// 只要队列不为空,就有访问的
// 挨个访问 队列中的结点
int node = queue.poll(); // 检索并删除此列表的标题(第一个元素)。也就是出队操作
// 根据结点node 得到新的可访问链表,即node结点可以访问到的结点 构成的列表
List<Integer> nextList = adj[node];
// 可能node结点 后面并没有 可以访问的结点了(可访问链表为空),就不考虑node结点了,结束本次循环考虑队列中下一个元素
if(nextList == null){
continue;
}
// 遍历从node结点得到的可访问链表
for (Integer next : nextList) {
if (next == target){ // 找到了直接返回true
return true;
}
// next并不是目标target
if (visited[next]){
// 如果已经访问过了,就不再处理
continue;
}
// node是start可以到达的结点,next又是node可以到达的结点,所以next也是start可以到达的结点
// 标记为已访问,添加进可到达队列
visited[next] = true;
queue.offer(next);
}
}
return false;
}
效果不怎么好,但是便于理解
补充,邻接表的转换示例:
有向图为:
@Test
public void test2() {
int n = 6;
int[][] graph = {
{0, 0},
{1, 2},
{1, 4},
{2, 5},
{3, 5},
{3, 0},
{4, 2},
{5, 4}};
toAdjTable(graph, n);
}
public void toAdjTable(int[][] graph, int n) {
List[] adj = new ArrayList[n];
for (int[] ints : graph) {
int from = ints[0];
int to = ints[1];
if (adj[from] == null) {
adj[from] = new ArrayList();
}
adj[from].add(to);
}
// 打印邻接表
for (int i = 0; i < adj.length; i++) {
System.out.println(i+" "+adj[i]);
}
}
输出结果:
0 [0]
1 [2, 4]
2 [5]
3 [5, 0]
4 [2]
5 [4]