-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprims.java
More file actions
120 lines (66 loc) · 2.19 KB
/
Copy pathprims.java
File metadata and controls
120 lines (66 loc) · 2.19 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package graphs;
import java.util.Scanner;
// Time complexity
// ---> O(V^2)
// using priority queue to find min O(V(l0gV+V))
// using pq and adjacency list: O((V+E)logV)
public class prims {
public static int findMinVertex(int weights[], boolean visited[], int n) {
int minVertex = -1;
for (int i = 0; i < n; i++) {
if (visited[i] == false && (minVertex == -1 || weights[i] < weights[minVertex])) {
minVertex = i;
}
}
return minVertex;
}
public static void primAlgo(int[][] edges, int V) {
int parent[] = new int[V];
int weights[] = new int[V];
boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
weights[i] = Integer.MAX_VALUE;
}
parent[0] = -1;
weights[0] = 0;
for (int i = 0; i < V; i++) {
int minVertex = findMinVertex(weights, visited, V);
visited[minVertex] = true;
for (int j = 0; j < V; j++) {
if (edges[minVertex][j] != 0 && visited[j] == false) {
if (edges[minVertex][j] < weights[j]) {
weights[j] = edges[minVertex][j];
parent[j] = minVertex;
}
}
}
}
for (int i = 1; i < V; i++) {
if (parent[i] < i) {
System.out.println(parent[i] + " " + i + " " + weights[i]);
} else {
System.out.println(i + " " + parent[i] + " " + weights[i]);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
int edges[][] = new int[V][V];
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
edges[i][j] = 0;
}
}
for (int i = 0; i < E; i++) {
int f = sc.nextInt();
int s = sc.nextInt();
int w = sc.nextInt();
edges[f][s] = w;
edges[s][f] = w;
}
primAlgo(edges, V);
}
}