naev 0.12.5
union_find.c
Go to the documentation of this file.
1/*
2 * See Licensing and Copyright notice in naev.h
3 */
9#include "union_find.h"
10
11#include "array.h"
12
14void unionfind_init( UnionFind *uf, int n )
15{
16 uf->parent = array_create_size( int, n );
17 uf->rank = array_create_size( int, n );
18 for ( int i = 0; i < n; i++ ) {
19 array_push_back( &uf->parent, i );
20 array_push_back( &uf->rank, 0 );
21 }
22}
23
26{
27 array_free( uf->parent );
28 uf->parent = NULL;
29 array_free( uf->rank );
30 uf->rank = NULL;
31}
32
34void unionfind_union( UnionFind *uf, int x, int y )
35{
36 x = unionfind_find( uf, x );
37 y = unionfind_find( uf, y );
38 if ( uf->rank[x] > uf->rank[y] )
39 uf->parent[y] = x;
40 else {
41 uf->parent[x] = y;
42 if ( uf->rank[x] == uf->rank[y] )
43 uf->rank[y]++;
44 }
45}
46
48int unionfind_find( UnionFind *uf, int x )
49{
50 if ( uf->parent[x] != x )
51 uf->parent[x] = unionfind_find( uf, uf->parent[x] );
52 return uf->parent[x];
53}
54
58{
59 int *a = array_create( int );
60 for ( int i = 0; i < array_size( uf->parent ); i++ )
61 if ( uf->parent[i] == i )
62 array_push_back( &a, i );
63 return a;
64}
Provides macros to work with dynamic arrays.
#define array_free(ptr_array)
Frees memory allocated and sets array to NULL.
Definition array.h:170
#define array_create_size(basic_type, capacity)
Creates a new dynamic array of ‘basic_type’ with an initial capacity.
Definition array.h:102
static ALWAYS_INLINE int array_size(const void *array)
Returns number of elements in the array.
Definition array.h:179
#define array_push_back(ptr_array, element)
Adds a new element at the end of the array.
Definition array.h:134
#define array_create(basic_type)
Creates a new dynamic array of ‘basic_type’.
Definition array.h:93
Disjoint set forest on {0, .., n-1}.
Definition union_find.h:7
int * parent
Definition union_find.h:8
int * rank
Definition union_find.h:9
int * unionfind_findall(UnionFind *uf)
Returns a designated representative of each subset in an array (array.h).
Definition union_find.c:57
int unionfind_find(UnionFind *uf, int x)
Finds the designated representative of the subset containing x.
Definition union_find.c:48
void unionfind_init(UnionFind *uf, int n)
Creates a UnionFind structure on {0, ..., n}.
Definition union_find.c:14
void unionfind_union(UnionFind *uf, int x, int y)
Declares x and y to be in the same subset.
Definition union_find.c:34
void unionfind_free(UnionFind *uf)
Frees resources associated with uf.
Definition union_find.c:25