Created
January 11, 2018 22:14
-
-
Save jianminchen/b3a96e8f05647ef65ad5b2c1e13df696 to your computer and use it in GitHub Desktop.
Quick find class - study union find algorithm following the blog: http://blog.csdn.net/dm_vincent/article/details/7655764
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
/// <summary> | |
/// Study notes for the blog about union find | |
/// http://blog.csdn.net/dm_vincent/article/details/7655764 | |
/// Quick-find algorithm | |
/// </summary> | |
public class QuickFind | |
{ | |
private int[] id; // access to component id (site indexed) | |
private int count; // number of components | |
public QuickFind(int N) | |
{ | |
// Initialize component id array. | |
count = N; | |
id = new int[N]; | |
for (int i = 0; i < N; i++) | |
{ | |
id[i] = i; | |
} | |
} | |
public int GetCount() | |
{ | |
return count; | |
} | |
public bool Connected(int p, int q) | |
{ | |
return Find(p) == Find(q); | |
} | |
public int Find(int p) | |
{ | |
return id[p]; | |
} | |
public void Union(int p, int q) | |
{ | |
int pID = Find(p); | |
int qID = Find(q); | |
if (pID == qID) | |
{ | |
return; | |
} | |
// Find the pID, and make them one group | |
for (int i = 0; i < id.Length; i++) | |
{ | |
if (id[i] == pID) | |
{ | |
id[i] = qID; | |
} | |
} | |
// update count of groups | |
count--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment