-
Notifications
You must be signed in to change notification settings - Fork 1
/
DisjSets.h
executable file
·71 lines (59 loc) · 1.51 KB
/
DisjSets.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* DisjSets.h
* MazeInC
*
* Copyright 2009-2018 Matthew T. Pandina. All rights reserved.
*
*/
#ifndef DISJSETS_H
#define DISJSETS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
typedef int32_t *DisjSetsRef;
static inline void DisjSets_reset(DisjSetsRef djs, uint32_t size) {
memset(djs, 0xFF, sizeof(int32_t) * size); // quickly sets all int32_t's to -1
// The intent of the above code is:
// for (uint32_t i = 0; i < size; ++i)
// djs[i] = -1;
}
static inline DisjSetsRef DisjSets_create(uint32_t size) {
DisjSetsRef djs = (DisjSetsRef)malloc(sizeof(int32_t) * size);
DisjSets_reset(djs, size);
return djs;
}
static inline void DisjSets_delete(DisjSetsRef djs) {
free(djs);
}
static inline void DisjSets_union(DisjSetsRef djs, int32_t root1, int32_t root2) {
if (djs[root2] < djs[root1])
djs[root1] = root2;
else {
if (djs[root1] == djs[root2])
djs[root1] -= 1;
djs[root2] = root1;
}
}
static inline int DisjSets_find(DisjSetsRef djs, int32_t x) {
int root, var, prevVar;
root = var = x;
while (djs[root] >= 0)
root = djs[root];
while (djs[var] >= 0) {
prevVar = var;
var = djs[var];
djs[prevVar] = root;
}
return root;
}
static inline bool DisjSets_sameSet(DisjSetsRef djs, int32_t x, int32_t y) {
return (DisjSets_find(djs, x) == DisjSets_find(djs, y));
}
#ifdef __cplusplus
}
#endif
#endif // DISJSETS_H