您的位置:首页 > 其它

LeetCode133—Clone Graph

2016-07-31 22:40 381 查看

LeetCode133—Clone Graph

1.原题

果然上一题不是把上上题的结果返回在求最小值这么简单,那样就超时了,先跳一蛤吧。

原题链接

Clone an undirected graph. Each node in the graph contains a label and 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 0 to both nodes 1 and 2.

Second node is labeled as 1. Connect node 1 to node 2.

Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

1
/ \
/   \
0 --- 2
/ \
\_/


2.分析

定义了一种新的图数据结构,说白了就是遍历,考虑一个问题,当由于环的存在,例如{1 ,2#2 ,1}的期望拷贝应该是如下所示:

1 <—->2

而在我之前的版本中出现了两种错误结果:

错误1 : 1—–>2 //设置了单一vector作为搜索的visit,导致搜索完成后2那一部分直接跳过。

错误2: 1—>2 2—->1 // 这样解决了上述问题,但是创建了多于两个新的节点。

针对错误2,在Discuss区找到一个不错的解答Discuss解答

通过hash的方式来判断该节点是否已经被创建,没有则重新创建,否则直接返回指针。

3.代码

typedef UndirectedGraphNode Node;
class Solution
{
private:
Node * dfs(Node *node);
unordered_map<Node*,Node*>visit;
public:
Node*cloneGraph(Node *node);

};

Node* Solution::dfs(Node * node)
{
if(visit.find(node)==visit.end())
{
visit[node] = new Node(node->label);
for(int i=0;i<node->neighbors.size();i++)
{
Node *tmp=dfs(node->neighbors[i]);
visit[node]->neighbors.push_back(tmp);
}
}
return visit[node];
}
Node *Solution::cloneGraph(Node *node)
{
if(NULL==node)
return NULL;
return dfs(node);

}


4.后记

DFS和BFS再熟悉不过了,但换一换数据结构就变得有难度了,感觉火候不够,还需多练,之后会补充BFS和非递归的DFS,加油~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: