-
Notifications
You must be signed in to change notification settings - Fork 10
/
BreadthFirstSearch.java
71 lines (57 loc) · 1.92 KB
/
BreadthFirstSearch.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
package com.camnter.basicexercises.graph;
import com.camnter.basicexercises.core.AdjacencyMatrixGraph;
import java.util.LinkedList;
import java.util.Queue;
/**
* 图 广度优先搜索(BFS)
* <p/>
* 类似于 树 BFS
*
* @author CaMnter
*/
public class BreadthFirstSearch<T> {
public void bfs(AdjacencyMatrixGraph<T> graph) {
boolean[] visited = new boolean[graph.getNumOfVertex()];
Queue<T> queue = new LinkedList<T>();
final int size = graph.vertexes.size();
for (int i = 0; i < size; i++) {
// 没访问过该 顶点
if (visited[i]) continue;
T t;
t = graph.vertexes.get(i);
/**
* 入队 && 标记
*/
queue.add(t);
visited[i] = true;
System.out.print(t.toString() + " ");
while (!queue.isEmpty()) {
queue.poll();
for (int j = 0; j < size; j++) {
/**
* 排除 访问过 && 自己连自己的无效矩阵点
*/
if (visited[j] || j == i) continue;
/**
* 矩阵内确认是否有 边
*/
if (graph.adjacencyMatrix[i][j] == 0) continue;
/**
* 边上的另外一点 && 没访问过
*/
t = graph.vertexes.get(j);
/**
* 入队 && 标记
*/
visited[j] = true;
queue.add(t);
System.out.print(t.toString() + " ");
}
}
}
}
public static void main(String[] args) {
BreadthFirstSearch<String> breadthFirstSearch = new BreadthFirstSearch<String>();
breadthFirstSearch.bfs(AdjacencyMatrixGraph.getBiggerGraph());
}
}