Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8975712

Browse files
Added Clone Graph
1 parent 7dd7399 commit 8975712

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

LeetcodeProblems/Clone_Graph.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
Clone Graph
3+
https://leetcode.com/problems/clone-graph/description/
4+
5+
Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label (int) and a list (List[UndirectedGraphNode]) of its neighbors. There is an edge between the given node and each of the nodes in its neighbors.
6+
7+
8+
OJ's undirected graph serialization (so you can understand error output):
9+
Nodes are labeled uniquely.
10+
11+
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
12+
13+
14+
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
15+
16+
The graph has a total of three nodes, and therefore contains three parts as separated by #.
17+
18+
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
19+
Second node is labeled as 1. Connect node 1 to node 2.
20+
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
21+
22+
23+
Visually, the graph looks like the following:
24+
25+
1
26+
/ \
27+
/ \
28+
0 --- 2
29+
/ \
30+
\_/
31+
Note: The information about the tree serialization is only meant so that you can understand error output if you get a wrong answer.
32+
You don't need to understand the serialization to solve the problem.
33+
*/
34+
35+
/**
36+
* Definition for undirected graph.
37+
* function UndirectedGraphNode(label) {
38+
* this.label = label;
39+
* this.neighbors = []; // Array of UndirectedGraphNode
40+
* }
41+
*/
42+
43+
/**
44+
* @param {UndirectedGraphNode} graph
45+
* @return {UndirectedGraphNode}
46+
*/
47+
var cloneGraph = function(graph) {
48+
if(!graph)
49+
return graph;
50+
51+
return dfs(graph, {});
52+
};
53+
54+
var dfs = function(graph, visited) {
55+
if(visited[graph.label])
56+
return visited[graph.label];
57+
58+
var newNode = new UndirectedGraphNode(graph.label);
59+
visited[newNode.label] = newNode;
60+
61+
for(var i = 0; i < graph.neighbors.length; i++) {
62+
const neighbor = dfs(graph.neighbors[i], visited);
63+
newNode.neighbors.push(neighbor);
64+
}
65+
66+
return newNode;
67+
}

0 commit comments

Comments
 (0)