# 133. Clone Graph

{% embed url="<https://leetcode.com/problems/clone-graph/description/>" %}

### DFS

```jsx
/**
 * @param {Node} node
 * @return {Node}
 */

let m;
var cloneGraph = function (node) {
    if (node === null) 
        return null;
    
    m = new Map();
    return dfs(node);
};

function dfs(node) {

    if (m.get(node.val) !== undefined) 
        return m.get(node.val);
    
    const cloned = new Node(node.val, []);
    m.set(node.val, cloned);
    
    for (const there of node.neighbors) {
        cloned.neighbors.push(dfs(there));
    }

    return cloned;
}
Console
```

### Iteration

> time: O(n)

> space: O(n)

```jsx
/**
 * // Definition for a Node.
 * function Node(val, neighbors) {
 *    this.val = val === undefined ? 0 : val;
 *    this.neighbors = neighbors === undefined ? [] : neighbors;
 * };
 */

/**
 * @param {Node} node
 * @return {Node}
 */
var cloneGraph = function (node) {
    if (node === null) return null;

    const m = {};
    const visited = new Set();

    const q = [node];
    while (q.length > 0) {
        const here = q.shift();

        if (visited.has(here.val)) continue;
        
        m[here.val] = m[here.val] ?? new Node(here.val, []);

        for (const there of here.neighbors) {
            m[there.val] = m[there.val] ?? new Node(there.val, []); 
            m[here.val].neighbors.push(m[there.val]);
            q.push(there);
        }

        visited.add(here.val);
    }

    return m[node.val];
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/graph/133.-clone-graph.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
