Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 11, 2018 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/b3a96e8f05647ef65ad5b2c1e13df696 to your computer and use it in GitHub Desktop.
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
/// <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