-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrim.java
More file actions
executable file
·68 lines (67 loc) · 2.39 KB
/
Prim.java
File metadata and controls
executable file
·68 lines (67 loc) · 2.39 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
package com.company;
import java.util.*;
public class Prim {
private final int m = 10000;
void print_path(int a,int b,int w){
System.out.println(" "+a+" ---> "+b+"\t "+w);
}
void prim_algo(int G[][]){
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
System.out.println("From To\tWeight");
Map<Integer,Integer> edges = new HashMap();
HashMap<Integer,Integer> val = new HashMap<>();
ArrayList<Integer> union = new ArrayList<>();
ArrayList<HashMap<Integer,Integer>> values = new ArrayList<>();
edges.put(0,0);
for (int i=1;i<G.length;i++)
{
edges.put(i,Integer.MAX_VALUE);
}
int index=0;
while (edges.size()!=0){
if (edges.containsKey(index)){
for (int j=0;j<G.length;j++)
{
if(G[index][j]!=0&&edges.containsKey(j)){
if(G[index][j]<edges.get(j)){
priorityQueue.add(G[index][j]);
val.put(G[index][j],j);
val.put(m,index);
}
}
}}
edges.remove(index);
union.add(index);
if(values.isEmpty()){
int min = priorityQueue.poll();
print_path(val.get(m),val.get(min),min);
index = val.get(min);
val.remove(min);
HashMap<Integer,Integer> map2 = new HashMap<>();
map2.putAll(val);
values.add(map2);
val.clear();
}
else {
int min = priorityQueue.poll();
int source=0;
HashMap<Integer,Integer> map2 = new HashMap<>();
map2.putAll(val);
values.add(map2);
val.clear();
int dest=0;
for(int i=0;i<values.size();i++){
if(values.get(i).containsKey(min)){
source = values.get(i).get(m);
dest = values.get(i).get(min);
values.get(i).remove(min);
break;
}
}
if(!union.contains(dest)){
print_path(source,dest,min);
index = dest;
}
}}
}
}