數據結構Java版之廣度優先圖(十三)

廣度優先,則是用的隊列,將每一層的節點先存入隊列中去,後依次取出隊列中的節點,顯示與當前節點存在邊,可是未被訪問過的節點,也就是下一層與之相聯繫的節點,再將這些節點存入隊列。通過層層迭代,就能夠徹底遍歷java

整個圖。測試

  源碼:this

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;
        }
    }

}

測試程序:spa

    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();
    }

測試結果:code

01010
10001
00001
10001
01110
A    B    D    E    C    
相關文章
相關標籤/搜索