Topics / Data Structures & Algorithms / Q24
Clone a graph in C without sharing the original nodes.
Short answer: Create one new node for each original node, then reconnect edges using a mapping from original node ID to its clone. This preserves cycles and shared neighbors.
#include <stdbool.h>
#include <stddef.h>
#define N 8
struct node {
int value;
unsigned degree;
struct node *next[N];
};
/* Source edges must point into src[0..N-1]. Arrays disjoint. */
bool clone(const struct node src[N], struct node dst[N])
{
for (unsigned i = 0; i < N; i++) {
if (src[i].degree > N) return false;
for (unsigned j = 0; j < src[i].degree; j++) {
unsigned k = 0;
while (k < N && src[i].next[j] != &src[k]) k++;
if (k == N) return false;
}
}
for (unsigned i = 0; i < N; i++) {
dst[i] = (struct node){.value = src[i].value,
.degree = src[i].degree};
for (unsigned j = 0; j < src[i].degree; j++) {
unsigned k = 0;
while (src[i].next[j] != &src[k]) k++;
dst[i].next[j] = &dst[k];
}
}
return true;
}
If A→B and B→A, the clones point to one another, not the originals. The caller owns the destination storage. The linear pointer lookup costs O(V+EV); stable vertex IDs or a hash map reduce it to O(V+E). This fixed-size approach avoids heap allocation.