zoukankan      html  css  js  c++  java
  • [LeetCode]133. Clone Graph

    复制图

    分别使用bfs和dfs

    1:bfs

    /**
     * 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) return NULL;
            unordered_map<UndirectedGraphNode*,UndirectedGraphNode*> mp;
            queue<UndirectedGraphNode*> toVisit;
            
            UndirectedGraphNode* copy = new UndirectedGraphNode(node->label);
            mp[node]=copy;
            toVisit.push(node);
            while(!toVisit.empty()){
                UndirectedGraphNode* cur = toVisit.front();
                toVisit.pop();
                for(UndirectedGraphNode* neigh:cur->neighbors){
                    if(mp.find(neigh)==mp.end()){
                        UndirectedGraphNode* neigh_copy = new UndirectedGraphNode(neigh->label);
                        mp[neigh]=neigh_copy;
                        toVisit.push(neigh);
                    }
                    mp[cur]->neighbors.push_back(mp[neigh]);
                }
            }
            return copy;
        }
    
        
    };

    2、dfs

    class Solution {
    public:
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
            if (!node) return NULL;
            if (mp.find(node) == mp.end()) {
                mp[node] = new UndirectedGraphNode(node -> label);
                for (UndirectedGraphNode* neigh : node -> neighbors)
                    mp[node] -> neighbors.push_back(cloneGraph(neigh));
            }
            return mp[node];
        } 
    private:
        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
    };
  • 相关阅读:
    6.Mysql之MGR的限制和局限性
    5.Mysql之MGR原理浅谈02
    2.shell之cut详解
    1.Shell编程的基本语法01
    4.Mysql之MGR浅谈01
    3.Mysql之MHA实战(03)
    2.Mysql之高可用架构MHA(02)
    1.数据库的三大范式是什么?
    1.Mysql之主从复制浅谈01
    6.Mydumper和Myloader备份恢复
  • 原文地址:https://www.cnblogs.com/bright-mark/p/9602959.html
Copyright © 2011-2022 走看看