Graph的算法实现: 寻找一幅图的最小生成树(MST)

来源:互联网 发布:阿里云如何搭建ssr 编辑:程序博客网 时间:2024/06/06 09:41

一个graph 只有一个最小生成树(minimum spanning tree). 寻找最小生成树有两个算法, 一个是Prim‘s algorithm, 另一个是Kruskal's algoritm。 关于具体的算法不再赘述。 下面给出Java代码和注释。 由于我使用的编程语言是C++, 但是通过下面给出的hint, 很容修改为C++ 的实现代码。

//Prim's algorithms in java//from you Tube video, part1 and part2import java.util.Scanner;public class PrimProgram {   static Scanner scan;   public static void main(String[] args) {      scan = new Scanner(System.in); // objects takes input from the user    int [][] matrix = new int [5][5] // suppose our graph has 5 nodes, then our weight matrix is 5 x 5  int[] visted = new int[5]; // this array keeps track of the nodes we have visited  int min; // minimum variable to store the minimum of the array  int u = 0; // initialize starting vertex as node 0;  int v = 0;// v is the ending vertex of the edge  int total = 0;     // take input from the user to initialize the 2-D array, sor two nested for loops  for (int i = 0; i < 5; i++) {      visited[i] = 0; // because non of them has been visited     for (int j = 0; j < 5; j++) {    matrix[i][j] = scan.nextInt(); // input integers from the userif(matrix[i][j] == 0) {   matrix[i][j] = 999; // because no infinity in computer language} }}  visited[0] = 1; //start of the algorithm for (inr counter = 0; counter < 4; counter++) {  // why four times, because i have 5 nodes, and a MST for 5 nodes has 4 edges    min = 999; // initialize min to 999// go through all the visited nodes array, and then check the edges which is connected //to it has minimum values, andI find it(which has the minimum value) , take that node, //and mark it as the visited, and repeat the process exactle// 4 times, because 4 is the number of edges you are going to havefor (int i = 0; i < 5; i++) {    if(visited[i] == 1) {     // check if i is visited, so the first node, 0 is visited, we then go into the body, and....      //then check either of these edges is smallest    for (int j = 0; j < 5; j++) {     if(visited[j] != 1 ) {    //only if j is not visited, we runif (min > matrix[i][j]) {// min is 999, if it is greater than current value   min = matrix[i][j]; // the weight of edge (i, j)    u = i;    v = j;} }  }   }}             visted[v] = 1;// note that v is equal to j and is already visited, and you don't want to do it again, so mark it as visitedtotal += min; // calculate the total cost(incrementing), you know, they are making the spanning tree right now.            // print the edges which has already happened            System.out.println("Edge found: " + u + "->" + v + "Weight:" + min);   }  // outside the biggest loop, which iterates 4 times System.out.println("The weight fo the minimmum spanning tree is: " + total);  }     }    

0 0
原创粉丝点击