图算法-MST最小生成树
2021/12/16 14:11:48
本文主要是介绍图算法-MST最小生成树,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Minimum cost to connect all cities
-
Difficulty Level : Medium
-
There are n cities and there are roads in between some of the cities. Somehow all the roads are damaged simultaneously. We have to repair the roads to connect the cities again. There is a fixed cost to repair a particular road. Find out the minimum cost to connect all the cities by repairing roads. Input is in matrix(city) form, if city[i][j] = 0 then there is not any road between city i and city j, if city[i][j] = a > 0 then the cost to rebuild the path between city i and city j is a. Print out the minimum cost to connect all the 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; } }
这篇关于图算法-MST最小生成树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-11cursor试用出现:Too many free trial accounts used on this machine 的解决方法
- 2025-01-11百万架构师第十四课:源码分析:Spring 源码分析:深入分析IOC那些鲜为人知的细节|JavaGuide
- 2025-01-11不得不了解的高效AI办公工具API
- 2025-01-102025 蛇年,J 人直播带货内容审核团队必备的办公软件有哪 6 款?
- 2025-01-10高效运营背后的支柱:文档管理优化指南
- 2025-01-10年末压力山大?试试优化你的文档管理
- 2025-01-10跨部门协作中的进度追踪重要性解析
- 2025-01-10总结 JavaScript 中的变体函数调用方式
- 2025-01-10HR团队如何通过数据驱动提升管理效率?6个策略
- 2025-01-10WBS实战指南:如何一步步构建高效项目管理框架?