数据结构Java版之广度优先图(十三)
广度优先,则是用的队列,将每一层的节点先存入队列中去,后依次取出队列中的节点,显示与当前节点存在边,但是未被访问过的节点,也就是下一层与之相联系的节点,再将这些节点存入队列。经过层层迭代,就可以完全遍历
整个图。
源码:
package mygraph; import java.util.LinkedList; import java.util.Queue; public class BFS_Vertex { class Vertex { private char lable; private int val; private boolean wasvisited; Vertex(char lable) { this.lable = lable; } Vertex() { } } private char lable; // 矩阵元素 private Vertex[][] list = new Vertex[20][20]; private Vertex[] vertexList = new Vertex[20]; private int nVerts; // 当前顶点下标 BFS_Vertex() { this.nVerts = 0; for(int i = 0; i < 20; i ++) { for(int j = 0; j < 20; j ++) { list[i][j] = new Vertex(); } } } // 增加一个顶点 public void addVertex(char lable) { vertexList[nVerts++] = new Vertex(lable); } // 增加一条边 public void addEdge(int start, int end) { list[start][end].val = 1; list[end][start].val = 1; } // 打印矩阵 public void printMatrix() { for (int i = 0; i < nVerts; i++) { for (int j = 0; j < nVerts; j++) { System.out.print(list[i][j].val); } System.out.println(); } } //显示字符 public void showVertex(int v) { System.out.print(vertexList[v].lable + "\t"); } //获得邻接未访问节点 public int getAdjUnvisitedVertex(int v) { for(int j = 0; j < nVerts; j ++) { if((list[v][j].val == 1) && (vertexList[j].wasvisited == false)) { return j; } } return -1; } //BFS public void BFS() { LinkedList q = new LinkedList(); vertexList[0].wasvisited = true; showVertex(0); q.add(0); int ver1, ver2; while(q.size() > 0) { ver1 = (int) q.poll(); ver2 = getAdjUnvisitedVertex(ver1); while(ver2 != -1) { vertexList[ver2].wasvisited = true; showVertex(ver2); q.add(ver2); ver2 = getAdjUnvisitedVertex(ver1); } } for(int j = 0; j < nVerts; j ++) { vertexList[j].wasvisited = false; } } }
测试程序:
public static void main(String[] args) { BFS_Vertex ds = new BFS_Vertex(); ds.addVertex('A'); //0 ds.addVertex('B'); //1 ds.addVertex('C'); //2 ds.addVertex('D'); //3 ds.addVertex('E'); //4 ds.addEdge(0, 1); //A-B ds.addEdge(0, 3); //A-D ds.addEdge(1, 4); //B-E ds.addEdge(3, 4); //D-E ds.addEdge(4, 2); //E-C ds.printMatrix(); ds.BFS(); }
测试结果:
01010
10001
00001
10001
01110
A B D E C