Skip to content

Commit

Permalink
Create Solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
Mansi8874 authored Jan 27, 2024
1 parent 50074d1 commit 08ab3ef
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Day-29/Q2 : Min Cost to Connect All Points/Solutions
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
class Solution {
class Edge{
int src;
int dest;
int wt;
public Edge(int s,int d,int w){
this.src=s;
this.dest=d;
this.wt=w;
}
}
class Pair implements Comparable<Pair>{
int node;
int cost;
public Pair(int s,int d){
this.node=s;
this.cost=d;
}
public int compareTo(Pair p2){
return this.cost-p2.cost;
}
}
public int minCostConnectPoints(int[][] points) {
ArrayList<Edge> graph[]=new ArrayList[points.length];
for(int i=0;i<graph.length;i++){
graph[i]=new ArrayList<Edge>();
}
for(int i=0;i<points.length;i++){
int x1=points[i][0];
int y1=points[i][1];
for(int j=i+1;j<points.length;j++){
int x2=points[j][0];
int y2=points[j][1];
int wt=Math.abs(x1-x2)+Math.abs(y1-y2);
graph[i].add(new Edge(i,j,wt));
graph[j].add(new Edge(j,i,wt));
}
}
return helper(graph,points.length);
}
public int helper(ArrayList<Edge> graph[],int v) {
boolean vis[] = new boolean[v];
PriorityQueue<Pair> pq = new PriorityQueue<>();

pq.add(new Pair(0, 0)); //you can choose any pair. i choose 0
int ans = 0;
while(pq.size() != 0){
Pair curr = pq.remove();
if(!vis[curr.node]){
ans += curr.cost;
vis[curr.node] = true;
for(int i=0;i<graph[curr.node].size();i++){
Edge e=graph[curr.node].get(i);
if(!vis[e.dest]){
pq.add(new Pair(e.dest,e.wt));
}
}
}
}
return ans;
}
}

0 comments on commit 08ab3ef

Please sign in to comment.