Java用邻接矩阵实现广度优先

来源:互联网 发布:如果黄家驹还活着知乎 编辑:程序博客网 时间:2024/06/08 01:32

定义节点类:

//一个节点class Vertex{    char label;    boolean wasVisited;    public Vertex(char label){        this.label = label;        wasVisited = false;     }}

图:

class Graph{    private final int MAX_VERTS = 20;    private Vertex vertexList[];//节点列表    private int adjMat[][];//邻接矩阵    private int nVerts;//节点数    private Queue theQueue;//协助队列    public Graph(){        vertexList = new Vertex[MAX_VERTS];        adjMat = new int[MAX_VERTS][MAX_VERTS];        nVerts = 0;        for(int i = 0; i < MAX_VERTS; i++){            for(int j = 0; j < MAX_VERTS; j++)                adjMat[i][j] = 0;        }        theQueue = new ArrayDeque();    }    public void addVertex(char lab){        vertexList[nVerts++] = new Vertex(lab);    }    public void addEdge(int start, int end){        adjMat[start][end] = 1;        adjMat[end][start] = 1;    }    public void displayVertex(int v){        System.out.print(vertexList[v].label);    }    //获取为v节点邻接的未被访问的节点    public int getAdjUnvisiedVertex(int v){        for(int i = 0; i < nVerts; i++){            if(adjMat[v][i] == 1 && vertexList[i].wasVisited == false){                return i;            }        }        return -1;    }    //广度优先搜索    /**     * 规则1:访问下一个未来访问的邻接点(如果存在),这个顶点必须是当前顶点的邻接点,标记为已访问,并把它插入到队列中     *      *      * 规则2:如果因为已经没有未访问顶点而不能执行规则1,那么从队列头取一个顶点(如果存在),并使其     * 称为当前顶点     *      * 规则3:如果因为队列为空而不能执行规则2,则搜索结束     */    public void bfs(){        vertexList[0].wasVisited = true;        displayVertex(0);;        theQueue.offer(0);        int v2;        while( !theQueue.isEmpty()){            int v1 = (int) theQueue.remove();            while((v2 = getAdjUnvisiedVertex(v1)) != -1){                vertexList[v2].wasVisited = true;                displayVertex(v2);                theQueue.offer(v2);            }        }        for(int i = 0; i < nVerts; i++){            vertexList[i].wasVisited = false;        }    }   }

测试:

        Graph theGraph = new Graph();        theGraph.addVertex('A');        theGraph.addVertex('B');        theGraph.addVertex('C');        theGraph.addVertex('D');        theGraph.addVertex('E');        theGraph.addVertex('F');        theGraph.addVertex('G');        theGraph.addVertex('H');        theGraph.addVertex('I');        theGraph.addEdge(0, 1);//AB        theGraph.addEdge(0, 2);//AC        theGraph.addEdge(0, 3);//AD        theGraph.addEdge(0, 4);//AE        theGraph.addEdge(1, 5);//BF        theGraph.addEdge(5, 6);//FG        theGraph.addEdge(3, 6);//DG        theGraph.addEdge(6, 7);//GI        theGraph.bfs();

广度优先搜索:ABCDEFGH

6 0
原创粉丝点击