【LeetCode】Clone Graph (2 solutions)

Clone Graph

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. 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
         /          \_/

这题只需一边遍历一遍复制就可以了。

因此至少可以用三种方法:

1、广度优先遍历(BFS)

2、深度优先遍历(DFS)

2.1、递归

2.2、非递归

解法一:广度优先遍历

变量说明:

hash表m用来保存原图结点与克隆结点的对应关系。

hash表f用来记录已经访问过的原图结点,防止循环访问。

队列q用于记录深度优先遍历的层次信息。

/**
 * 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 NULL;

        map<UndirectedGraphNode *, UndirectedGraphNode *> m; //record the <original node, clone node> pairs
        map<UndirectedGraphNode *, bool> f; //record original nodes that have been dealt with
        queue<UndirectedGraphNode *> q; //BFS, q store the original node
        UndirectedGraphNode *nodeClone = new UndirectedGraphNode(node->label);
        m[node] = nodeClone;  //add <node, ret> to map
        q.push(node);
        f[node] = true;

        while(!q.empty())
        {
            UndirectedGraphNode *temp = q.front();  //original node
            UndirectedGraphNode *tempClone = (m.find(temp))->second;   //clone node
            q.pop();
            for(vector<UndirectedGraphNode *>::size_type st = 0; st < temp->neighbors.size(); st ++)
            {//add neighbors of temp to the queue
                UndirectedGraphNode *neighbor = temp->neighbors[st];
                map<UndirectedGraphNode *, bool>::iterator itf = f.find(neighbor);
                if(itf == f.end())
                {
                    f[neighbor] = true;
                    q.push(neighbor);
                }

                map<UndirectedGraphNode *, UndirectedGraphNode *>::iterator it = m.find(neighbor);

                UndirectedGraphNode *neighborClone;
                if(it == m.end())
                {//neighbors[st] not constructed yet
                    neighborClone = new UndirectedGraphNode(neighbor->label);
                    m[neighbor] = neighborClone;
                }
                else
                    neighborClone = it->second;

                //connect neighbor to tempClone
                tempClone->neighbors.push_back(neighborClone);
            }
        }
        return nodeClone;
    }
};

解法二:递归深度优先遍历(DFS)

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    map<UndirectedGraphNode *, UndirectedGraphNode *> f;

    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node)
    {
        if(node == NULL)
            return NULL;

        map<UndirectedGraphNode *, UndirectedGraphNode *>::iterator it = f.find(node);
        if(it != f.end())   //if node is visited, just return the recorded nodeClone
            return f[node];

        UndirectedGraphNode *nodeClone = new UndirectedGraphNode(node->label);
        f[node] = nodeClone;
        for(vector<UndirectedGraphNode *>::size_type st = 0; st < node->neighbors.size(); st ++)
        {
            UndirectedGraphNode *temp = cloneGraph(node->neighbors[st]);
            if(temp != NULL)
                nodeClone->neighbors.push_back(temp);
        }
        return nodeClone;
    }
};

时间: 2024-10-01 21:48:05

【LeetCode】Clone Graph (2 solutions)的相关文章

【leetcode】Clone Graph(python)

类似于二叉树的三种遍历,我们可以基于遍历的模板做很多额外的事情,图的两种遍历,深度和广度模板同样也可以做很多额外的事情,这里举例利用深度优先遍历的模板来进行复制,深度优先中,我们先访问第一个结点,接着访问第一个邻接点,再访问邻节点的邻节点.... class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if None =

【leetcode】Clone Graph

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 neigh

【LeetCode】Clone Graph 解题报告

[题目] 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

【Leetcode】 Clone Graph

题目链接:https://leetcode.com/problems/clone-graph/ 题目: 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

【LeetCode】Single Number (2 solutions)

Single Number Given an array of integers, every element appears twice except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解法一:用map记录每个元素的次数,返回次数为1的元素 cl

【LeetCode】Reverse Integer (2 solutions)

Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have alread

【LeetCode】Same Tree (2 solutions)

Same Tree Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 解法一:递归 /** * Definition for binary tree * struct TreeNod

【LeetCode】Plus One (2 solutions)

Plus One Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. 从个位数字往前扫,只要一个数字不为9,即可加1返回. 如果直到最高位仍为9,则说明结果为100…0 解法一: 可能会使用额外空间与复制

【LeetCode】Generate Parentheses (2 solutions)

Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "