I'm using union-find algorithm to find all the connected components of an un-directed graph. For some unknown reasons it gives a wrong answer. The input graph that I give is connected and yet it outputs 2 different labels for that graph.
I would be glad if someone can explain this anomaly. Are there some special undirected graphs where Union-Find may not work?
** The graph is a little big, so I added a picture for better readability of the graph. couldn't trim the graph or the essence of the question will vanish. **
Here, p and rk are parent and rank respectively.
Code
Union function
void union_find(int x, int y, int *p, int *rk)
{
int px = find(x, p);
int py = find(y, p);
if(px != py)
{
if(rk[px] < rk[py])
{
p[px] = py;
}
else
{
p[py] = px;
if(rk[px] == rk[py]) rk[px]++;
}
}
}
Find function
int find(int x , int *p)
{
return (p[x] == x) ? x : p[x] = find(p[x], p);
}
Sample Input
37 51
4 5
4 10
5 7
5 8
5 9
6 7
6 16
7 8
7 15
8 9
8 10
10 11
10 14
11 12
12 21
13 14
13 32
14 15
14 22
15 16
15 22
16 17
17 22
17 19
19 24
19 27
20 30
20 32
21 31
22 23
22 36
23 24
23 36
24 25
25 26
26 36
26 27
27 28
27 29
27 32
27 37
28 29
29 30
31 32
32 33
32 35
33 34
33 35
34 35
35 36
36 37
Photo of the graph
Please note that, I'm not considering the nodes 1,2,3 and 18 and their edges.