
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
// Union-Find data structure for disjoint sets
typedef struct {
int *parent;
int *rank;
int size;
} UnionFind;
UnionFind *uf_create(int n) {
UnionFind *uf = (UnionFind *)malloc(sizeof(UnionFind));
uf->size = n;
uf->parent = (int *)malloc(n * sizeof(int));
uf->rank = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
uf->parent[i] = i;
uf->rank[i] = 0;
}
return uf;
}
int uf_find(UnionFind *uf, int x) {
if (uf->parent[x] != x)
uf->parent[x] = uf_find(uf, uf->parent[x]);
return uf->parent[x];
}
void uf_union(UnionFind *uf, int x, int y) {
int rootX = uf_find(uf, x);
int rootY = uf_find(uf, y);
if (rootX != rootY) {
if (uf->rank[rootX] < uf->rank[rootY]) {
uf->parent[rootX] = rootY;
} else if (uf->rank[rootX] > uf->rank[rootY]) {
uf->parent[rootY] = rootX;
} else {
uf->parent[rootY] = rootX;
uf->rank[rootX]++;
}
}
}
int removeStones(int stones[][2], int stonesSize) {
int maxCoord = 0;
for (int i = 0; i < stonesSize; i++) {
if (stones[i][0] > maxCoord) maxCoord = stones[i][0];
if (stones[i][1] > maxCoord) maxCoord = stones[i][1];
}
UnionFind *uf = uf_create(2 * (maxCoord + 1));
for (int i = 0; i < stonesSize; i++) {
// Union row index with column index offset by maxCoord + 1
uf_union(uf, stones[i][0], stones[i][1] + maxCoord + 1);
}
int connectedComponents = 0;
int *visited = (int *)calloc(2 * (maxCoord + 1), sizeof(int));
for (int i = 0; i < stonesSize; i++) {
int root = uf_find(uf, stones[i][0]);
if (!visited[root]) {
visited[root] = 1;
connectedComponents++;
}
}
free(visited);
free(uf->parent);
free(uf->rank);
free(uf);
return stonesSize - connectedComponents;
}
int main() {
int stones1[][2] = {{0,0}, {0,1}, {1,0}, {1,2}, {2,1}, {2,2}};
int size1 = sizeof(stones1) / sizeof(stones1[0]);
printf("%d\n", removeStones(stones1, size1)); // Output: 5
int stones2[][2] = {{0,0}, {0,2}, {1,1}, {2,0}, {2,2}};
int size2 = sizeof(stones2) / sizeof(stones2[0]);
printf("%d\n", removeStones(stones2, size2)); // Output: 3
int stones3[][2] = {{0,0}};
int size3 = sizeof(stones3) / sizeof(stones3[0]);
printf("%d\n", removeStones(stones3, size3)); // Output: 0
return 0;
}