leetcode练习 Clone Graph

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
题目说用一种方法表示图,属于题目自己的方便,跟代码没啥关系,就不放了,反正就是个克隆图。这次继续熟悉unordered_map
对应关系就是原图对应克隆图,代码如下:

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (!node) return node;
        unordered_map map;
        UndirectedGraphNode* copy = new UndirectedGraphNode(node->label);
        map[node] = copy;
        queue q;
        q.push(node);
        while(!q.empty()) {
            UndirectedGraphNode* cur = q.front();
            q.pop();
            for (auto x: cur->neighbors) {
                if (map.find(x) == map.end()) {
                    UndirectedGraphNode* new_x = new UndirectedGraphNode(x->label);
                    map[x] = new_x;
                    q.push(x);
                }
            }
            for (auto x: cur->neighbors) {
                map[cur]->neighbors.push_back(map[x]);
            }
        }
        return copy;
    }
};

你可能感兴趣的:(学习)