You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
本题是MST(最小生成树)算法,每个点到点的边有一个cost,求连接所有点的最小cost。
思路:
最小生成树算法有Kruskal算法和Prim算法。
Kruskal算法是每次加一条边,Prim算法是每次加一个点。
这里用Prim算法(因为它的代码比较短)。
贴别人一张图(链接)
可以看到Prim算法是把所有点逐步加入到MST的过程。
首先以某点为出发点(这里以0为出发点),把出发点0加入MST(boolean数组中true的点),
遍历MST中的所有点,计算其他点和它们连接的cost,形成(nextNode, cost),把它们加入list,
这时候要注意,已经在MST中的点就不要再重复计算了。
下次再选出cost最小的nextNode当作出发点(这是当前出发点对应的cost最小边的另一头的点),重复这一过程,直到所有点都在MST中(用一个count计数)。
实现的时候,如果用list,每次都要找cost最小的,比较耗时,不如直接用最小堆minHeap,每次直接取cost最小的(node, cost)对,
添加的时候也是O(logn)复杂度。
*Java SE9中已经有Pair类了,可以直接用Pair(node, cost)。
public int minCostConnectPoints(int[][] points) {
PriorityQueue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>(
(a, b)->(a.getValue() - b.getValue())); //(node, weight)
int n = points.length;
boolean[] inMST = new boolean[n];
int minCost = 0;
int usedNode = 0; //处理过与node相连接的点后才算used
minHeap.add(new Pair(0, 0)); //node 0, weight 0
while(usedNode < n) {
Pair<Integer, Integer> cur = minHeap.poll(); //取出weight最小的(node, cost)
int curNode = cur.getKey();
int curWeight = cur.getValue();
if(inMST[curNode]) continue; //选出来的边的另一顶点已经在MST中了,跳过
minCost += curWeight; //加上cost
inMST[curNode] = true; //MST中加入新的点
usedNode ++;
//以新加入的点为顶点,找到与它连接的所有点,加到minHeap中,供下次挑选
for(int nextNode = 0; nextNode < n; nextNode ++) {
if(inMST[nextNode]) continue;
int nextWeight = Math.abs(points[curNode][0] - points[nextNode][0]) +
Math.abs(points[curNode][1] - points[nextNode][1]);
minHeap.add(new Pair(nextNode, nextWeight));
}
}
return minCost;
}