forked from SnowScriptWinterOfCode/LeetCode_Q
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |