Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit da490d1

Browse files
add: Clone Graph
1 parent 9d4b634 commit da490d1

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
3434
|91|[Decode Ways](https://leetcode.com/problems/decode-ways/) | [JavaScript](./src/decode-ways/res.js)|Medium|
3535
|120|[Triangle](https://leetcode.com/problems/triangle/) | [JavaScript](./src/triangle/res.js)|Medium|
3636
|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | [JavaScript](./src/surrounded-regions/res.js)|Medium|
37+
|133|[Clone Graph](https://leetcode.com/problems/clone-graph/) | [JavaScript](./src/clone-graph/res.js)|Medium|
3738
|136|[Single Number](https://leetcode.com/problems/single-number/) | [JavaScript](./src/single-number/res.js)|Easy|
3839
|152|[Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | [JavaScript](./src/maximum-product-subarray/res.js)|Medium|
3940
|175|[Combine Two Tables](https://leetcode.com/problems/combine-two-tables/)| [SQL](./src/combine-two-tables/res.txt)|Easy|

‎src/clone-graph/res.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* res.js
3+
* @authors Joe Jiang (hijiangtao@gmail.com)
4+
* @date 2017年04月16日 22:11:56
5+
*
6+
* Problem: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
7+
*
8+
* Definition for undirected graph.
9+
* function UndirectedGraphNode(label) {
10+
* this.label = label;
11+
* this.neighbors = []; // Array of UndirectedGraphNode
12+
* }
13+
*/
14+
15+
/**
16+
* @param {UndirectedGraphNode} graph
17+
* @return {UndirectedGraphNode}
18+
*/
19+
let cloneGraph = function(graph) {
20+
// if (!graph) return graph;
21+
let res = {};
22+
return iterateGraph(graph);
23+
24+
function iterateGraph(subgraph) {
25+
if (!subgraph) {
26+
return subgraph;
27+
}
28+
29+
let id = subgraph.label;
30+
if (!res[id]) {
31+
res[id] = new UndirectedGraphNode(id);
32+
res[id].neighbors = subgraph.neighbors.map(iterateGraph);
33+
}
34+
35+
return res[id];
36+
}
37+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /