The game of Hex is played on an n times n board composed of
Solution
function Find(p)
if p.parentRoot != p
p.parentRoot := Find(p.parentRoot)
return p.parentRoot
function Union(p, q)
xRoot := Find(p)
yRoot := Find(q)
// if both values are in same set
if xRoot == yRoot
return
// if both p and q are not in same set, we need to merge them
if xRoot.rank < yRoot.rank
xRoot.parentRoot := yRoot
else if xRoot.rank > yRoot.rank
yRoot.parentRoot := xRoot
else
//make new parentRoot to be one root
yRoot.parentRoot := xRoot
xRoot.rank := xRoot.rank + 1
----------------------------------------------------------------------------------------------------------------------------
Idea behind this find-union method to solve hex game is..
When new piece is placed, then it gives new equivalence class. Then its neighbours of same
colors need to merge. Also each edge on board will have different color virtual stones.
So if edge stone having same color will oppose virtual edge stones, then connection will made and finish the game.
--------------------------------------------------------------------------------------
Coming to complexity of this algorithm is..
As find method takes O(n) time since it needs to traverse entire tree height in worst case.
So combinely union-find algorithm will takes O(n) running time complexity.
