1
+ /*
2
+ Author: Annie Kim, [email protected]
3
+ Date: Sep 26, 2013
4
+ Problem: Clone Graph
5
+ Difficulty: Easy
6
+ Source: http://oj.leetcode.com/problems/clone-graph/
7
+ Notes:
8
+ Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
9
+
10
+ OJ's undirected graph serialization:
11
+ Nodes are labeled from 0 to N - 1, where N is the total nodes in the graph.
12
+ We use # as a separator for each node, and , as a separator for each neighbor of the node.
13
+ As an example, consider the serialized graph {1,2#2#2}.
14
+ The graph has a total of three nodes, and therefore contains three parts as separated by #.
15
+ Connect node 0 to both nodes 1 and 2.
16
+ Connect node 1 to node 2.
17
+ Connect node 2 to node 2 (itself), thus forming a self-cycle.
18
+ Visually, the graph looks like the following:
19
+
20
+ 1
21
+ / \
22
+ / \
23
+ 0 --- 2
24
+ / \
25
+ \_/
26
+
27
+ Solution: 1. DFS. 2. BFS.
28
+ */
29
+
30
+ /* *
31
+ * Definition for undirected graph.
32
+ * struct UndirectedGraphNode {
33
+ * int label;
34
+ * vector<UndirectedGraphNode *> neighbors;
35
+ * UndirectedGraphNode(int x) : label(x) {};
36
+ * };
37
+ */
38
+ class Solution {
39
+ public:
40
+ typedef UndirectedGraphNode GraphNode;
41
+ typedef unordered_map<GraphNode *, GraphNode *> MAP;
42
+
43
+ GraphNode *cloneGraph (GraphNode *node) {
44
+ return cloneGraph_1 (node);
45
+ }
46
+
47
+ // DFS
48
+ GraphNode *cloneGraph_1 (GraphNode *node) {
49
+ MAP map;
50
+ return cloneGraphRe (node, map);
51
+ }
52
+
53
+ GraphNode *cloneGraphRe (GraphNode *node, MAP &map) {
54
+ if (!node) return NULL ;
55
+ if (map.find (node) != map.end ())
56
+ return map[node];
57
+ GraphNode *newNode = new GraphNode (node->label );
58
+ map[node] = newNode;
59
+ for (int i = 0 ; i < node->neighbors .size (); ++i)
60
+ newNode->neighbors .push_back (cloneGraphRe (node->neighbors [i], map));
61
+ return newNode;
62
+ }
63
+
64
+ // BFS
65
+ GraphNode *cloneGraph_2 (GraphNode *node) {
66
+ if (!node) return NULL ;
67
+ queue<GraphNode*> q;
68
+ q.push (node);
69
+ MAP map;
70
+ map[node] = new GraphNode (node->label );
71
+ while (!q.empty ())
72
+ {
73
+ GraphNode *oriNode = q.front (); q.pop ();
74
+ GraphNode *newNode = map[oriNode];
75
+ for (int i = 0 ; i < oriNode->neighbors .size (); ++i)
76
+ {
77
+ GraphNode *oriNeighbor = oriNode->neighbors [i];
78
+ if (map.find (oriNeighbor) != map.end ()) {
79
+ newNode->neighbors .push_back (map[oriNeighbor]);
80
+ continue ;
81
+ }
82
+ GraphNode *newNeighbor = new GraphNode (oriNeighbor->label );
83
+ newNode->neighbors .push_back (newNeighbor);
84
+ map[oriNeighbor] = newNeighbor;
85
+ q.push (oriNeighbor);
86
+ }
87
+ }
88
+ return map[node];
89
+ }
90
+ };
0 commit comments