邻接表的BFS

来源:互联网 发布:淘宝充话费始终不到账 编辑:程序博客网 时间:2024/06/07 06:12
import java.util.Arrays;import java.util.LinkedList;class Vertex {public char v;// vertexprivate LinkedList<Vertex> nextList = null;// 与v相邻的vertex集合public int color;// 0:white 1:gray 2:blackprivate int index;// constructorVertex(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 constructorAdjTabGraph() {this(MAX_VERTEX_NUM, false);}// have-args constructorAdjTabGraph(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]);}}// bfspublic 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);}}

原创粉丝点击