-
Notifications
You must be signed in to change notification settings - Fork 2
/
UNDirectedGraph.java
126 lines (109 loc) · 2.9 KB
/
UNDirectedGraph.java
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package homework.graph;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
/**
* 无向图
*/
public class UNDirectedGraph {
//顶点个数
private int v;
private LinkedList<Integer>[] adj;
public UNDirectedGraph(int v){
this.v = v;
this.adj = new LinkedList[v];
for(int i=0;i<v;i++){
this.adj[i] = new LinkedList<>();
}
}
public void addEdge(int s,int t){
adj[s].add(t);
adj[t].add(s);
}
/**
* 广度优先搜索:搜索从s到t的最短路径,并且打印
* @param s
* @param t
*/
public void bfs(int s,int t){
boolean[] visited = new boolean[v];
int[] pre = new int[v];//pre[i]表示到达i节点的前一个节点
Arrays.fill(pre,-1);
Queue<Integer> queue = new LinkedList<>();
queue.offer(s);
boolean find = false;
while(!queue.isEmpty()){
int n = queue.poll();
if(n==t){
find = true;
break;
}
if(adj[n]!=null){
for(Integer to : adj[n]){
if(visited[to]){
continue;
}
pre[to] = n;
visited[to] = true;
queue.offer(to);
}
}
}
if(find){
printPath(pre,s,t);
}else{
System.out.println("未找到");
}
}
private void printPath(int[] pre, int s, int t) {
if(s!=t){
printPath(pre,s,pre[t]);
}
System.out.print(t+"->");
}
/**
* 深度优先搜索,搜索从s到t的一条路径
* @param s
* @param t
*/
public void dfs(int s,int t){
boolean[] visited = new boolean[this.v];
int[] pre = new int[this.v];
Arrays.fill(pre,-1);
visited[s] = true;
dfs(s,t,visited,pre);
printPath(pre,s,t);
}
private boolean dfs(int s, int t, boolean[] visited, int[] pre) {
if(s == t){
return true;
}
for(int i=0;i<adj[s].size();i++){
int to = adj[s].get(i);
if(!visited[to]){
visited[to] = true;
pre[to] = s;
if(dfs(adj[s].get(i),t,visited,pre)){
return true;
}
}
}
return false;
}
public static void main(String[] args){
UNDirectedGraph ugraph = new UNDirectedGraph(8);
ugraph.addEdge(0,1);
ugraph.addEdge(0,3);
ugraph.addEdge(1,2);
ugraph.addEdge(1,4);
ugraph.addEdge(3,4);
ugraph.addEdge(2,5);
ugraph.addEdge(4,5);
ugraph.addEdge(4,6);
ugraph.addEdge(5,7);
ugraph.addEdge(6,7);
ugraph.bfs(0,7);
System.out.println();
ugraph.dfs(0,7);
}
}