-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_162cities.java
More file actions
42 lines (42 loc) · 1.27 KB
/
_162cities.java
File metadata and controls
42 lines (42 loc) · 1.27 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
import java.util.*;
public class _162cities {
static class Edge implements Comparable<Edge>{
int dest;
int cost;
public Edge(int d, int c){
this.dest=d;
this.cost=c;
}
@Override
public int compareTo(Edge e2){
return this.cost-e2.cost;
}
}
public static int connectCitites(int cities[][]){
PriorityQueue<Edge> pq = new PriorityQueue<>();
boolean vis[] = new boolean[cities.length];
pq.add(new Edge(0,0));
int finalCost =0;
while(!pq.isEmpty()){
Edge curr = pq.remove();
if(!vis[curr.dest]){
vis[curr.dest]=true;
finalCost += curr.cost;
for(int i=0;i<cities[curr.dest].length;i++){
if(cities[curr.dest][i] != 0){
pq.add(new Edge(i,cities[curr.dest][i]));
}
}
}
}
return finalCost;
}
public static void main(String[] args) {
int cities[][]={{0,1,2,3,4},
{1,0,5,0,7},
{2,5,0,6,0},
{3,0,6,0,0},
{4,7,0,0,0}};
System.out.println(connectCitites(cities));
}
}