-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindPathInGraphv2.java
More file actions
57 lines (50 loc) · 1.49 KB
/
FindPathInGraphv2.java
File metadata and controls
57 lines (50 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package chapter9;
import java.util.*;
/*
* 题目描述
对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),
请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
*/
public class FindPathInGraphv2 {
/*
public class UndirectedGraphNode {
int label = 0;
UndirectedGraphNode left = null;
UndirectedGraphNode right = null;
ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>();
public UndirectedGraphNode(int label) {
this.label = label;
}
}*/
public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) {
// write code here
if(null == a || null == b)
return false;
return FindPath(a,b) || FindPath(b, a);
}
public static boolean FindPath(UndirectedGraphNode a, UndirectedGraphNode b)
{
LinkedList<UndirectedGraphNode> quque = new LinkedList<UndirectedGraphNode>();
HashSet<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
quque.add(a);
while(!quque.isEmpty())
{
UndirectedGraphNode tmp = quque.removeFirst();
set.add(tmp);
if(b == tmp)
return true;
else {
for(UndirectedGraphNode v:tmp.neighbors)
{
if(!set.contains(v))
quque.add(v);
}
}
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}