[LeetCode] Clone Graph
2014-12-25 17:00
330 查看
Clone an undirected graph. Each node in the graph contains a
a list of its
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
a separator for node label and each neighbor of the node.
As an example, consider the serialized graph
The graph has a total of three nodes, and therefore contains three parts as separated by
First node is labeled as
both nodes
Second node is labeled as
node
Third node is labeled as
node
Visually, the graph looks like the following:
labeland
a list of its
neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
#as a separator for each node, and
,as
a separator for node label and each neighbor of the node.
As an example, consider the serialized graph
{0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by
#.
First node is labeled as
0. Connect node
0to
both nodes
1and
2.
Second node is labeled as
1. Connect node
1to
node
2.
Third node is labeled as
2. Connect node
2to
node
2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(node == NULL) return NULL; unordered_map<UndirectedGraphNode *,UndirectedGraphNode *> nodeMap; queue<UndirectedGraphNode *> visit; visit.push(node); UndirectedGraphNode * copyNode = new UndirectedGraphNode(node -> label); nodeMap[node] = copyNode; while(visit.size() > 0){ UndirectedGraphNode *cur = visit.front(); visit.pop(); for(int i = 0;i < cur -> neighbors.size();i ++){ UndirectedGraphNode *neighbor = cur -> neighbors[i]; if(nodeMap.find(neighbor) == nodeMap.end()){ UndirectedGraphNode *neighborCopy = new UndirectedGraphNode(neighbor -> label); nodeMap[cur] -> neighbors.push_back(neighborCopy); nodeMap[neighbor] = neighborCopy; visit.push(neighbor); }else{ nodeMap[cur] ->neighbors.push_back(nodeMap[neighbor]); } } } return copyNode; } };
相关文章推荐
- leetcode [Clone Graph] Java
- [LeetCode] Clone Graph
- leetcode Clone Graph
- LeetCode: Clone Graph
- leetcode——133——Clone Graph
- [LeetCode] Clone Graph
- LeetCode | Clone Graph(克隆图)
- leetcode 日经贴,Cpp code -Clone Graph
- [Leetcode]Clone Graph
- leetcode-Clone Graph
- *Leetcode_clone-graph(c++ version)
- LeetCode: Clone Graph 解题报告
- LeetCode Clone Graph
- leetcode : Clone Graph
- [Leetcode]Clone Graph
- leetcode — clone-graph
- leetcode:Clone Graph
- [LeetCode][Java] Clone Graph
- 【leetcode】Clone Graph
- Clone Graph [leetcode] dfs和bfs