Java实现图的存储

GA666666 2021-05-26 PM 22℃ 0条

代码:

package maze;

public class Main {
    public static void main(String[] args) {
        int graph[][] = {{0,1,3,4,7},{1,0,2,99999,99999},{3,2,0,5,8},{4,99999,5,0,6},{7,99999,8,6,0}};
        MatGraph g = new MatGraph();
        CreateGraph(g, graph, 5, 5);
        DisGraph(g);
        Prim(g,0);
    }
    public static void Prim(MatGraph g,int v) {
        System.out.println("Min Create Graph\n");
        int lowcost[] = new int[5];
        int closest[] = new int[5];
        int min,k;
        for(int i=0; i<g.n; i++) {
            lowcost[i] = g.edges[v][i];
            closest[i] = v;
        }
        for(int i=0; i<g.n; i++) {
            min =65548;
            k = -1;
            for(int j=0; j<g.n; j++)
                if(lowcost[j]!=0&&lowcost[j]<min) {
                    min = lowcost[j];
                    k = j;
                }
            if(k>=0){
                System.out.println(" 边("+closest[k]+","+k+"),权值为"+min);
                lowcost[k] = 0;
            }
                
            for(int j=0; j<g.n; j++)
                if(lowcost[j] !=0&&g.edges[k][j]<lowcost[j]) {
                    lowcost[j] = g.edges[k][j];
                    closest[j] = k;
                }        
        }
        System.out.println();
        System.out.println("Min Create Graph End");
    }
    public static void CreateGraph(MatGraph g, int A[][], int n, int e) {
        g.setN(n);
        g.setE(e);
        int[][] a = new int[5][5];
        for (int i = 0; i < g.n; i++) {
            for (int j = 0; j < g.n; j++){
                //System.out.println(A[i][j]);
                a[i][j] = A[i][j];
                g.setEdges(a);
            }
                
        }
        System.out.println(" Create MatGraph Successfully!");
    }
    public static void DisGraph(MatGraph g) {
        System.out.println("--------------Start--------------");
        for (int i = 0; i < g.n; i++) {
            for (int j = 0; j < g.n; j++)
                if (g.edges[i][j] < 68845)
                    System.out.print(g.edges[i][j]+"\t");
                else
                    System.out.print("∞\t");
            System.out.println();
        }
        System.out.println("--------------E n d--------------");
    }
}

class VType {
    int adjvex;
    char VertexType[];
}

class MatGraph {
    int n, e;
    VType vexs[];
    int edges[][];

    public int getN() {
        return n;
    }

    public void setN(int n) {
        this.n = n;
    }

    public int getE() {
        return e;
    }

    public void setE(int e) {
        this.e = e;
    }

    public VType[] getVexs() {
        return vexs;
    }

    public void setVexs(VType[] vexs) {
        this.vexs = vexs;
    }

    public int[][] getEdges() {
        return edges;
    }

    public void setEdges(int[][] edges) {
        this.edges = edges;
    }

}

运行截图:请输入图片描述

标签: none

非特殊说明,本博所有文章均为博主原创。

评论啦~