-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathGraphBFS.java
More file actions
77 lines (65 loc) · 1.94 KB
/
GraphBFS.java
File metadata and controls
77 lines (65 loc) · 1.94 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Copyright © https://github.com/microwind All rights reserved.
* @author: jarryli@gmail.com
* @version: 1.0
*/
/**
* 图的广度优先搜索(BFS)算法实现
* 使用队列数据结构,按层次遍历图
*
* 时间复杂度: O(V + E),其中V是顶点数,E是边数
* 空间复杂度: O(V),用于存储访问标记和队列
*/
import java.util.LinkedList;
import java.util.Queue;
class GraphBFS {
private static final int V = 5;
/**
* 广度优先搜索遍历
* @param graph 邻接矩阵表示的图
* @param start 起始顶点
*/
public static void bfs(int[][] graph, int start) {
// 使用队列存储待访问的顶点
Queue<Integer> queue = new LinkedList<>();
// 访问标记数组
boolean[] visited = new boolean[V];
// 将起始顶点入队并标记为已访问
queue.offer(start);
visited[start] = true;
System.out.println("BFS traversal:");
// 当队列不为空时继续遍历
while (!queue.isEmpty()) {
// 出队一个顶点
int vertex = queue.poll();
System.out.println("Visited " + vertex);
// 遍历所有邻接顶点
for (int i = 0; i < V; i++) {
// 如果存在边且未被访问,则入队
if (graph[vertex][i] == 1 && !visited[i]) {
queue.offer(i);
visited[i] = true;
}
}
}
}
public static void main(String[] args) {
// 邻接矩阵表示的无向图
int[][] graph = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0}
};
bfs(graph, 0);
}
}
/*打印结果
jarry@Mac bfs % java GraphBFS.java
BFS traversal:
Visited 0
Visited 1
Visited 3
Visited 2
*/