1319. Number of Operations to Make Network Connected(並查集)

package Union_Find;

public class MakeConnected_1319 {
	// 1319. Number of Operations to Make Network Connected
	
	int[] P;
	// 剩餘的線
	int count;
	public int makeConnected(int n, int[][] connections) {
		P=new int[n];
		count=connections.length;
		// 初始化
		for(int i=0;i<n;i++) {
			P[i]=i;
		}
		for(int i=0;i<connections.length;i++) {
			union(connections[i][0],connections[i][1]);
		}
		
		if(count<n-(connections.length-count+1)) {
			// 如果剩餘的線小於剩餘的電腦數
			return -1;
		}else {
			return count;
		}
	}
	private int find(int x) {
		return P[x] == x ? x : (P[x] = find(P[x]));	//路徑壓縮
	}
	
	private void union(int x,int y) {
		int xRoot=find(x);
		int yRoot=find(y);
		if(xRoot!=yRoot) {
			P[xRoot]=yRoot;
			count--;
		}
	}
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章