Prim Primm Algorithm for Java implementation __ algorithm

Source: Internet
Author: User

The

  Primm algorithm, which is mainly used to find the minimum spanning tree, is simple to implement.

  Package algorithm; Import Java.util.Scanner; public class Prim {public static void main (string[] args) {Scanner sc = new Scanner (system.in); while (Sc.hasnext ()) {I NT n = sc.nextint (); int m = Sc.nextint (); if (n = = 0 && m = = 0) break; int[][] map = new Int[n][n]; for (int i = 0; i < n; ++i) {for (int j = 0; J < N; ++j) {map[i][j] = Integer.max_value;}} for (int i = 0; ; M ++i) {int u = sc.nextint (); int v = sc.nextint (); int w = Sc.nextint (); map[u][v] = w; Map[v][u] = w;} Edge[] e = new Edge[n]; Prime (map, E, n); for (int i = 0; i < n-1 ++i) {System.out.println (E[i].from + "" + E[i].end + "" + E[i].weight);}}} static void Prime (int[][] map, edge[] e, int n) {for (int i = 0; i < n-1; ++i) {E[i] = new Edge (); e[i].from = 0; E [I].end = i + 1; E[i].weight = map[0][i + 1]; for (int k = 1; k < n; ++k) {int m =-1; int min = Integer.max_value, for (int j = k-1; j < n-1; ++j) {if (E [J].weight < min] {min = e[j].weight;m = j; } Edge tmp = E[m]; E[M] = e[k-1]; E[K-1] = tmp; int c = k-1; for (int j = k; J < n-1; ++j) {int t = e[j].end; int w = e[j].weight; if (Map[e[c].end][t] < W) {E[j].from = E[c ].end; E[j].weight = Map[e[c].end][t]; }}} private static class Edge {int from; int weight;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.