编程语言
首页 > 编程语言> > 图算法-MST最小生成树

图算法-MST最小生成树

作者:互联网

Minimum cost to connect all cities

It is sure that all the cities were connected before the roads were damaged.

Examples: 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input : {{0, 1, 2, 3, 4},
         {1, 0, 5, 0, 7},
         {2, 5, 0, 6, 0},
         {3, 0, 6, 0, 0},
         {4, 7, 0, 0, 0}};
Output : 10

 

import java.io.*;
import java.util.*;

class GFG {
    public static void main (String[] args) {
        int[][] matrix = new int[][]{{0, 1, 1, 100, 0, 0},
         {1, 0, 1, 0, 0, 0},
         {1, 1, 0, 0, 0, 0},
         {100, 0, 0, 0, 2, 2},
         {0, 0, 0, 2, 0, 2},
         {0, 0, 0, 2, 2, 0}};
        System.out.println(getMinPath(matrix));
    }
    static class Edge{
        int x;
        int y;
        int value;
        Edge(int x,int y,int value){
            this.x=x;
            this.y=y;
            this.value=value;
        }
    }
    private static int getMinPath(int[][] matrix){
        int len = matrix.length;
        //1.create heap
        PriorityQueue<Edge> pq = new PriorityQueue<>((a,b)->a.value-b.value);
        //2.put the first element into heap
        Set<Integer> visited = new HashSet<>();
        visited.add(0);
        for(int i=0;i<len;i++) if(i!=0 && matrix[0][i]!=0) pq.offer(new Edge(0,i,matrix[0][i]));
        //3.while loop 
        int sum = 0;
        while(!pq.isEmpty()){
            Edge edge = pq.poll();
            if(visited.add(edge.y)){
                sum+=edge.value;
                for(int i=0;i<len;i++) if(i!=edge.y && matrix[edge.y][i]!=0) pq.offer(new Edge(edge.y,i,matrix[edge.y][i]));
            }
        }
        if(visited.size()==len) return sum;
        return -1;
    }
}

 

标签:city,matrix,int,MST,最小,value,算法,cost,cities
来源: https://www.cnblogs.com/cynrjy/p/15697369.html