Clone Graph
You get one node of a connected undirected graph; each node has a value and a list of its neighbours. Return a deep copy: new nodes with the same values and the same edges, and no link of the copy may lead to an old node. Our graph: a triangle 1 – 2 – 3 with a tail 3 – 4 – 5, and we get node 1. The answer is node 1′ of a new graph of the same shape: 1′ – 2′ – 3′ with the tail 3′ – 4′ – 5′.
- input
node: node 1 of a connected undirected graph, ornullfor an empty one. The tests write the graph as LeetCode does, its adjacency lists: the list atiholds the values of nodei + 1’sneighbors. Nodeihas the valuei.- returns
- A deep copy of the graph: new nodes with the same values and the same neighbors, in the same order; return the copy of
node. No node of the copy may be a node of the input. - constraints
- 0 ≤ the number of nodes ≤ 100
- every neighbor is a node of the graph, never the node itself, and listed once
- the graph is undirected and connected
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* // Definition for a _Node.
* function _Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {_Node} node
* @return {_Node}
*/
function cloneGraph(node) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more depth-first search (dfs) problems
- 104Maximum Depth of Binary TreeEasysolve
- 100Same TreeEasysolve
- 226Invert Binary TreeEasysolve
- 101Symmetric TreeEasysolve
- 112Path SumEasysolve
- 200Number of IslandsMediumsolve
- 695Max Area of IslandMediumsolve
- 417Pacific Atlantic Water FlowMediumsolve
- 129Sum Root to Leaf NumbersMediumsolve
- 222Count Complete Tree NodesMediumsolve
- 236Lowest Common Ancestor of a Binary TreeMediumsolve
- 130Surrounded RegionsMediumsolve
- 399Evaluate DivisionMediumsolve
- 124Binary Tree Maximum Path SumHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.