-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathPrims.java
More file actions
62 lines (43 loc) · 1.13 KB
/
Prims.java
File metadata and controls
62 lines (43 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int noOfNodes = sc.nextInt();
int numberOfEdges = sc.nextInt();
int[][] T = new int[noOfNodes][numberOfEdges];
int min = 0, result = 0;
boolean[] visited = new boolean[numberOfEdges];
int v = 0;
final int MAX_WEIGHT = 1000000;
for (int i = 0; i < noOfNodes; i++) {
Arrays.fill(T[i], MAX_WEIGHT);
}
for (int i = 0; i < numberOfEdges; i++) {
int firstNode = sc.nextInt() - 1;
int secondNode = sc.nextInt() - 1;
int weight = sc.nextInt();
T[firstNode][secondNode] = weight;
T[secondNode][firstNode] = T[firstNode][secondNode];
}
for (int k = 1; k <= noOfNodes; k++) {
min = MAX_WEIGHT;
for (int i = 0; i < numberOfEdges; i++) {
if (visited[i]){
for (int j = 0; j < numberOfEdges; j++) {
if (!visited[j]) {
if (min > T[i][j]) {
min = T[i][j];
v = j;
}
}
}
}
}
visited[v] = true;
if (min < MAX_WEIGHT)
result += min;
}
System.out.println(result);
sc.close();
}
}