並查集問題:簡單java實現

數據結構與算法分析章節


Java源碼實現

public class DisjSets {
	private int[] s = null;

	public DisjSets(int num) {
		s = new int[num];
		for (int i = 0; i < num; i++)
			s[i] = -1;
	}
	public void union(int root1, int root2) {
		if (s[root2] < s[root1])// root2 is deeper
			s[root1] = root2;
		else {
			if (s[root2] == s[root1])//Update height if same
				s[root1]--;
			s[root2] = root1;//Make root1 new root
		}
	}
	public int find(int x){
		if(s[x]<0)
			return x;
		else
			return s[x]=find(s[x]);
	}
}


發佈了24 篇原創文章 · 獲贊 17 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章