Skip to content

Commit c77c379

Browse files
committed
bfs
1 parent 2d3e9f6 commit c77c379

File tree

6 files changed

+100
-27
lines changed

6 files changed

+100
-27
lines changed

.idea/workspace.xml

Lines changed: 19 additions & 21 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
0 Bytes
Binary file not shown.
2.03 KB
Binary file not shown.
515 Bytes
Binary file not shown.

src/GraphBFS.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.util.ArrayList;
2+
import java.util.Queue;
3+
import java.util.LinkedList;
4+
5+
// 广度优先遍历
6+
public class GraphBFS {
7+
private Graph G;
8+
private boolean[] visited;
9+
private ArrayList<Integer> order = new ArrayList<>(); //先序遍历结果
10+
11+
public GraphBFS(Graph G){
12+
this.G = G;
13+
visited = new boolean[G.V()];
14+
15+
// 多包一层for,防止有多个联通分量
16+
for(int v = 0 ;v<G.V();v++){
17+
if(!visited[v])
18+
bfs(v);
19+
}
20+
}
21+
22+
// 广度优先遍历 , 路径同时是最短路径
23+
private void bfs(int s){
24+
Queue<Integer> queue = new LinkedList<>(); // LinkedList 实现了queue接口
25+
26+
// 入队并标记访问
27+
queue.add(s);
28+
visited[s] = true;
29+
30+
while(!queue.isEmpty()){
31+
int v = queue.remove(); //从队列取出元素
32+
order.add(v);
33+
34+
for(int w:G.adj(v)){
35+
if(!visited[w]) {
36+
// 入队并标记访问
37+
queue.add(w);
38+
visited[w] = true;
39+
}
40+
}
41+
}
42+
}
43+
44+
public Iterable<Integer> order(){
45+
return order;
46+
}
47+
48+
public static void main(String[] args){
49+
50+
Graph g = new Graph("g.txt");
51+
GraphBFS graphBFS = new GraphBFS(g);
52+
System.out.println(graphBFS.order());
53+
}
54+
55+
}

src/SingleSourcePath.java

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
import java.util.ArrayList;
2-
import java.util.Collection;
3-
import java.util.Collections;
1+
import java.util.*;
42

53
// 单源路径
64
public class SingleSourcePath {
75
private Graph G;
86
private int s;
97
private boolean[] visited;
10-
private int[] pre;
8+
private int[] pre; //上一个点
119

1210

1311
public SingleSourcePath(Graph G , int s){
@@ -20,8 +18,8 @@ public SingleSourcePath(Graph G , int s){
2018
for(int i=0;i<pre.length;i++)
2119
pre[i] = -1;
2220

23-
dfs(s,s);
24-
21+
//dfs(s,s);
22+
bfs(s);
2523
}
2624

2725
// 深度优先遍历
@@ -35,6 +33,28 @@ private void dfs(int v,int parent){
3533
}
3634
}
3735

36+
// 广度优先遍历
37+
private void bfs(int s){
38+
Queue<Integer> queue = new LinkedList<>(); // LinkedList 实现了queue接口
39+
40+
// 入队并标记访问
41+
queue.add(s);
42+
visited[s] = true;
43+
pre[s] = s;
44+
45+
while(!queue.isEmpty()){
46+
int v = queue.remove(); //从队列取出元素
47+
for(int w:G.adj(v)){
48+
if(!visited[w]) {
49+
// 入队并标记访问
50+
queue.add(w);
51+
visited[w] = true;
52+
pre[w] = v;
53+
}
54+
}
55+
}
56+
}
57+
3858
// 从源到目标是否可以连接
3959
public boolean isConnectedTo(int t){
4060
G.validateVertex(t);

0 commit comments

Comments
 (0)