力扣labuladong——一刷day82

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣261.以图判树
  • 二、力扣1135. 最低成本联通所有城市
  • 三、力扣261.以图判树


前言


最小生成树算法主要有 Prim 算法(普里姆算法)和 Kruskal 算法(克鲁斯卡尔算法)两种,这两种算法虽然都运用了贪心思想,但从实现上来说差异还是蛮大的。

一、力扣261.以图判树

boolean vaildTree(int n, int[][] edges){
	UF uf = new UF(n);
	for(int[] arr : edges){
		if(uf.connection(arr[0], arr[1])){
			return false;
		}else{
			uf.union(arr[0], arr[1]);
		}
	} 
	return uf.count == 1;
}

二、力扣1135. 最低成本联通所有城市

int minimumCost(int n, int[][] connections){
	int sum = 0;
	UF uf = new UF(n+1);
	Arrays.sort(connections,(a,b)->(a[2] - b[2]));
	for(int[] edge: connections){
		if(!uf.connection(edge[0], edge[1])){
			uf.union(edge[0], edge[1]);
			sum += edge[2];
		}
	}
	return uf.count == 2 : sum : -1;
}

三、力扣261.以图判树

class Solution {
    public int minCostConnectPoints(int[][] points) {
        int sum = 0;
        int n = points.length;
        UF uf = new UF(points.length);
        List<int[]> edges = new ArrayList<>();
        for(int i = 0; i < n; i ++){
            for(int j = 0; j < n; j ++){
                int x1 = points[i][0], y1 = points[i][1];
                int x2 = points[j][0], y2 = points[j][1];
                edges.add(new int[]{i, j, Math.abs(x1-x2)+Math.abs(y1-y2)});
            }
        }
        Collections.sort(edges,(a,b)->{return a[2] - b[2];});
        for(int[] edge : edges){
            if(!uf.getConnection(edge[0], edge[1])){
                sum += edge[2];
                uf.union(edge[0], edge[1]);
            }
        }
        return sum;
    }
    class UF{
        int count;
        int[] parent;
        public UF(int n){
            this.count = n;
            this.parent = new int[n];
            for(int i = 0; i < n; i ++){
                parent[i] = i;
            }
        }
        public int find(int x){
            if(parent[x] != x){
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }
        public void union(int x, int y){
            int rootx = find(x);
            int rooty = find(y);
            if(rootx == rooty){
                return;
            }
            parent[rootx] = rooty;
            count --;
        }
        public boolean getConnection(int x, int y){
            int rootx = find(x);
            int rooty = find(y);
            return rootx == rooty;
        }
        public int getCount(){
            return this.count;
        }
    }
}

你可能感兴趣的:(力扣题解,leetcode,java,算法,数据结构)