diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /clone_graph.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'clone_graph.c')
-rw-r--r-- | clone_graph.c | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/clone_graph.c b/clone_graph.c new file mode 100644 index 0000000..b47c9e8 --- /dev/null +++ b/clone_graph.c @@ -0,0 +1,35 @@ +// 133. Clone Graph +#include <stdbool.h> +#include <stdlib.h> + +// given reference of a node in a connected undirected graph. return a deep copy +// (clone) of the graph. each node in the graph contains a value (int) and a +// list (list[node]). + +struct Node { + int val; + int numNeighbors; + struct Node **neighbors; +}; + +struct Node *process(struct Node *s, bool *hash, struct Node **data) { + if (hash[s->val]) + return data[s->val]; + struct Node *root = malloc(sizeof(struct Node)); + root->val = s->val; + hash[s->val] = true; + data[s->val] = root; + root->numNeighbors = s->numNeighbors; + root->neighbors = malloc(s->numNeighbors * sizeof(struct Node *)); + for (int i = 0; i < s->numNeighbors; i++) + root->neighbors[i] = process(s->neighbors[i], hash, data); + return root; +} + +struct Node *cloneGraph(struct Node *s) { + if (s == NULL) + return NULL; + bool *hash = calloc(101, sizeof(int)); + struct Node **data = malloc(101 * sizeof(struct Node *)); + return process(s, hash, data); +} |