prim算法

class minMgraphTree {
    public void createMgraph(MGraph graph, int vertes, char[] vertex, int[][] weight) {
        for (int i = 0; i < vertes; i++) {
            graph.vertex[i] = vertex[i];
            for (int j = 0; j < vertes; j++) {
                graph.weights[i][j] = weight[i][j];
            }
        }
    }

    public void showMgraph(MGraph graph) {
        for (int[] vertex : graph.weights) {
            System.out.println(Arrays.toString(vertex));
        }
    }

    //普利姆算法實現
    public void prim(MGraph graph,int v) {
        //標記當前節點訪問狀態
        int visited[] = new int[graph.weights.length];
        visited[v] = 1;
        //h1 h2 記錄訪問過的節點
        int h1 = -1;
        int h2 = -1;
        //假設最小權值爲 MAX_VALUE
        int minWeight = Integer.MAX_VALUE;
        for (int i = 1; i < graph.vertexs; i++) {//n個頂點的圖生成的最小生成樹有n-1條邊
            for (int k = 0; k < graph.vertexs; k++) {//遍歷已經訪問過的節點
                for (int j = 0; j < graph.vertexs; j++) {//遍歷與已經訪問過節點相鄰的節點
                    if (visited[k] == 1 && visited[j] == 0 && graph.weights[i][k] < minWeight) {//找到當前子圖最小權的邊
                        minWeight = graph.weights[i][k];
                        h1 = j;
                        h2 = k;
                    }
                }
            }
            System.out.println("邊《" + h1 + "-" + h2 + "》權值爲" + minWeight);
            //標記當前節點爲已經訪問狀態
            visited[h2] = 1;
            //重新設置minWeight
            minWeight = Integer.MAX_VALUE;
        }
    }

    public void primAlgorithm(MGraph graph,int index) {
        int minWeight = 0;
        int m = -1;
        int[] flag =  new int[graph.vertexs];
        for (int i = 0; i < graph.vertexs; i++) {
            for (int j = 0; j < graph.vertexs; j++) {
                for (int k = 0; k < graph.vertexs; k++) {
                    if (flag[j] == 1 && flag[k] == 0) {
                        if (j == 0) {
                            minWeight = graph.weights[j][k];
                        }
                        if (graph.weights[j][k] < minWeight) {
                            minWeight = graph.weights[j][k];
                            m = k;
                        }
                    }
                }
            }
            flag[m] = 1;
        }
    }
}

class MGraph {
    int vertexs;
    char[] vertex;
    int[][] weights;

    public MGraph(int vertexs) {
        this.vertexs = vertexs;
        this.vertex = new char[vertexs];
        this.weights = new int[vertexs][vertexs];
    }
}

prim算法求最下生成樹

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章