LeetCode133—Clone Graph

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,加油~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值