import java.util.Arrays;
import java.util.LinkedList;
class Vertex {
public char v;// vertex
private LinkedList<Vertex> nextList = null;// 与v相邻的vertex集合
public int color;// 0:white 1:gray 2:black
private int index;
// constructor
Vertex(char ch) {
this.setV(ch);
this.setColor(0);
}
// 添加相邻顶点
public void addAdjVertex(Vertex adjVertex) {
if (nextList == null) {
nextList = new LinkedList<Vertex>();
}
nextList.add(adjVertex);
}
// 取得相邻顶点链表
public LinkedList<Vertex> getNextList() {
return nextList;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public char getV() {
return v;
}
public void setV(char v) {
this.v = v;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
}
class AdjTabGraph {
private final static int MAX_VERTEX_NUM = 20;// 缺省顶点数
private Vertex[] vertexSet;// 顶点集合
private boolean isDirected;// 是否有向
private int nVertexs;// 顶点实际个数
private LinkedList<Vertex> queue;
private int[] distance;// 源顶点与顶点u的距离为distance[u]
// no-args constructor
AdjTabGraph() {
this(MAX_VERTEX_NUM, false);
}
// have-args constructor
AdjTabGraph(int vertexNum, boolean flag) {
vertexSet = new Vertex[vertexNum];
isDirected = flag;
nVertexs = 0;
}
// 添加顶点
public void addVertex(Vertex v) {
vertexSet[nVertexs] = v;
vertexSet[nVertexs].setIndex(nVertexs);
nVertexs++;
}
// 添加边
public void addEdge(int startIndex, int endIndex) {
vertexSet[startIndex].addAdjVertex(vertexSet[endIndex]);
if (!isDirected) {
vertexSet[endIndex].addAdjVertex(vertexSet[startIndex]);
}
}
// bfs
public void breadthFirstSearch(int index) {
distance = new int[this.nVertexs];
Arrays.fill(distance, Integer.MAX_VALUE);
vertexSet[index].setColor(1);
distance[index] = 0;
queue = new LinkedList<Vertex>();
queue.add(vertexSet[index]);
while (!queue.isEmpty()) {
Vertex u = queue.removeFirst();
System.out.print("顶点" + u.getV() + " ");
for (int i = 0; i < u.getNextList().size(); i++) {
Vertex ui = u.getNextList().get(i);
if (ui.getColor() == 0) {
ui.setColor(1);
distance[ui.getIndex()] = distance[u.getIndex()] + 1;
queue.add(ui);
}
}
u.setColor(2);
}
}
}
public class Graph {
public static void main(String[] args) {
AdjTabGraph graph = new AdjTabGraph(7, false);
graph.addVertex(new Vertex('A'));
graph.addVertex(new Vertex('B'));
graph.addVertex(new Vertex('C'));
graph.addVertex(new Vertex('D'));
graph.addVertex(new Vertex('E'));
graph.addVertex(new Vertex('F'));
graph.addVertex(new Vertex('G'));
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(1, 5);
graph.addEdge(1, 4);
graph.addEdge(2, 3);
graph.addEdge(2, 6);
graph.addEdge(3, 5);
graph.addEdge(3, 6);
graph.breadthFirstSearch(4);
}
}
邻接表的BFS
最新推荐文章于 2024-08-03 08:36:03 发布