zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Clone Graph **@

    https://oj.leetcode.com/problems/clone-graph/

    图的拷贝,就是给一个图,再弄出一个一模一样的来。

    /**
     * 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 node;
            
            vector<UndirectedGraphNode *> allNode;
            unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> oldToNew;
            
            // 对于每一个node,都建立一个新node,把这关系存到map里面。之后对每个旧node,添加相应新node里的neighbour
            
            allNode.push_back(node);
            UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
            oldToNew.insert(make_pair(node,newNode));
                    
            int index = 0;
            UndirectedGraphNode *current;
            UndirectedGraphNode *neighNode;
            vector<UndirectedGraphNode *> neighbours;
            // build new nodes
            while(index < allNode.size())
            {
                current = allNode[index];
                index++;
                neighbours = current->neighbors;
                
                for(int i = 0; i < neighbours.size(); i++)
                {
                    neighNode = neighbours[i];
                    // 之前没有添加过它相应的
                    if(oldToNew.find(neighNode) == oldToNew.end())
                    {
                        UndirectedGraphNode *newNode = new UndirectedGraphNode(neighNode->label);
                        oldToNew.insert(make_pair(neighNode,newNode));
                        
                        allNode.push_back(neighNode);
                    }
                }
            }
            // build neighbours
            unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>::iterator itr;
            for(itr = oldToNew.begin(); itr!=oldToNew.end(); itr++)
            {
                current = itr->first;
                neighbours = current->neighbors;
                for(int i = 0; i < neighbours.size(); i++)
                {
                    itr->second->neighbors.push_back(oldToNew[neighbours[i]]);
                }
            }
            return oldToNew[node];
        }
    };
  • 相关阅读:
    poj 2388
    BUAA 1489
    poj 2524
    poj 2109
    poj 2503 Babelfish
    poj All in All
    poj 1611 The Suspects
    poj 2299
    poj 1328
    hdu 1008 Elevator
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3917015.html
Copyright © 2011-2022 走看看