Created
June 22, 2015 13:05
-
-
Save leighhalliday/5157ff3310f65c01535a to your computer and use it in GitHub Desktop.
Quick-Find & Quick-Union with Path Compression
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
class UnionFind | |
attr_accessor :nodes, :sizes | |
def initialize(num) | |
self.nodes = [] | |
self.sizes = [] | |
num.times do |n| | |
self.nodes[n] = n | |
self.sizes[n] = 1 | |
end | |
end | |
def root(i) | |
# Loop up the chain until reaching root | |
while nodes[i] != i do | |
# path compression for future lookups | |
nodes[i] = nodes[nodes[i]] | |
i = nodes[i] | |
end | |
i | |
end | |
def union(i, j) | |
rooti = root i | |
rootj = root j | |
# already connected | |
return if rooti == rootj | |
# root smaller to root of larger | |
if sizes[i] < sizes[j] | |
nodes[rooti] = rootj | |
sizes[rootj] += sizes[rooti] | |
else | |
nodes[rootj] = rooti | |
sizes[rooti] += sizes[rootj] | |
end | |
end | |
def connected?(i, j) | |
root(i) == root(j) | |
end | |
end | |
u = UnionFind.new(10) | |
p u.connected?(1, 4) | |
u.union(1,2) | |
u.union(2,3) | |
u.union(3,4) | |
u.union(5,2) | |
u.union(6,2) | |
u.union(6,7) | |
u.union(6,8) | |
p u.nodes | |
p u.connected?(1,4) | |
p u.connected?(2,4) | |
p u.connected?(1,8) | |
p u.nodes | |
p u.sizes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment