import java.util.*;

public class PrimAlgorithm {
    private int[][] graph; // 图的邻接矩阵
    private int[] lowCost; // lowCost[i]表示i到已选定的点集的最小边权
    private boolean[] visited; // visited[i]表示i是否已被加入已选定的点集
    private int[] parent; // parent[i]表示i在最小生成树中的父节点

    public PrimAlgorithm(int[][] graph) {
        this.graph = graph;
        int n = graph.length;
        lowCost = new int[n];
        visited = new boolean[n];
        parent = new int[n];
        Arrays.fill(lowCost, Integer.MAX_VALUE);
        Arrays.fill(visited, false);
        Arrays.fill(parent, -1);
    }

    public void prim() {
        int n = graph.length;
        int count = 0; // 已加入已选定的点集的节点数
        int sum = 0; // 最小生成树的权值之和
        lowCost[0] = 0;
        visited[0] = true;
        count++;
        while (count < n) {
            int minCost = Integer.MAX_VALUE;
            int minIndex = -1;
            // 找到一个未被加入已选定的点集的节点i,使得lowCost[i]最小
            for (int i = 0; i < n; i++) {
                if (!visited[i] && lowCost[i] < minCost) {
                    minCost = lowCost[i];
                    minIndex = i;
                }
            }
            if (minIndex == -1) {
                break; // 图不连通,退出循环
            }
            visited[minIndex] = true;
            count++;
            sum += minCost;
            // 更新lowCost和parent数组
            for (int i = 0; i < n; i++) {
                if (!visited[i] && graph[minIndex][i] < lowCost[i]) {
                    lowCost[i] = graph[minIndex][i];
                    parent[i] = minIndex;
                }
            }
        }
        if (count < n) {
            System.out.println("图不连通");
        } else {
            System.out.println("最小生成树的权值之和为:" + sum);
            System.out.print("最小生成树的边集为:");
            for (int i = 1; i < n; i++) {
                System.out.print("(" + parent[i] + "," + i + ") ");
            }
        }
    }

    public static void main(String[] args) {
        int[][] graph = {
                {0, 6, 1, 5, Integer.MAX_VALUE, Integer.MAX_VALUE},
                {6, 0, 5, Integer.MAX_VALUE, 3, Integer.MAX_VALUE},
                {1, 5, 0, 5, 6, 4},
                {5, Integer.MAX_VALUE, 5, 0, Integer.MAX_VALUE, 2},
                {Integer.MAX_VALUE, 3, 6, Integer.MAX_VALUE, 0, 6},
                {Integer.MAX_VALUE, Integer.MAX_VALUE, 4, 2, 6, 0}
        };
        PrimAlgorithm prim = new PrimAlgorithm(graph);
        prim.prim();
    }
}
``

原文地址: https://www.cveoy.top/t/topic/ffDT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录