复制无向图

复制无向图

http://www.nowcoder.com/questionTerminal/5ec76def9d7b420794091727a97f0dc6

首先,这是个图的问题,二话不说,咱先搬出BFSDFS两大法宝。

基本思路是:创建一个unordered_map,其中保存指向旧节点的指针到指向新节点的指针的映射,同时也用它来判断旧节点是否被遍历过。

BFS代码如下:

//
// Created by jt on 2020/9/23.
//
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;

class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (!node) return nullptr;
        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
        queue<UndirectedGraphNode*> qu;
        qu.push(node);
        // BFS
        while (!qu.empty()) {
            UndirectedGraphNode* oldNode = qu.front();
            qu.pop();
            UndirectedGraphNode* newNode = mp.count(oldNode) != 0
                    ? mp[oldNode] : new UndirectedGraphNode(oldNode->label);
            mp[oldNode] = newNode;
            for (auto p : oldNode->neighbors) {
                UndirectedGraphNode* q;
                if (mp.count(p) != 0) {
                    q = mp[p];
                } else {
                    q = new UndirectedGraphNode(p->label);
                    mp[p] = q;
                    // 如果旧节点没有遍历过,加入队列
                    qu.push(p);
                }
                newNode->neighbors.push_back(q);
            }
        }
        return mp[node];
    }
};

DFS代码如下:

//
// Created by jt on 2020/9/23.
//
#include <vector>
#include <unordered_map>
using namespace std;

class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (!node) return nullptr;
        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
        return dfs(node, mp);
    }

    UndirectedGraphNode* dfs(UndirectedGraphNode *node, unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> &mp) {
        if (!node) return nullptr;
        if (mp.count(node) != 0) return mp[node];
        UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
        mp[node] = newNode;
        for (auto p : node->neighbors) {
            newNode->neighbors.push_back(dfs(p, mp));
        }
        return newNode;
    }
};
刷遍天下无敌手 文章被收录于专栏

秋招刷题历程

全部评论

相关推荐

牛客101244697号:这个衣服和发型不去投偶像练习生?
点赞 评论 收藏
分享
想去夏威夷的小哥哥在度假:5和6才是重点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务