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
/ \
\_/

对图的遍历就是两个经典的方法DFS和BFS,和138. Copy List with Random Pointer思路一样,用一个HashMap记录原图节点和复制图节点间的对应关系,以防止重复建立节点,key存原始值,value存copy的值,用DFS,BFS方法遍历帮助拷贝neighbors的值。和那题的不同在于遍历原图相对比linked list的情况复杂一点。可以用BFS或DFS来遍历原图。而HashMap本身除了记录对应关系外,还有记录原图中每个节点是否已经被visit的功能。

Java: DFS

public class Solution {
private HashMap<Integer, UndirectedGraphNode> map = new HashMap<>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
return clone(node);
} private UndirectedGraphNode clone(UndirectedGraphNode node) {
if (node == null) return null; if (map.containsKey(node.label)) {
return map.get(node.label);
}
UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
map.put(clone.label, clone);
for (UndirectedGraphNode neighbor : node.neighbors) {
clone.neighbors.add(clone(neighbor));
}
return clone;
}
} 

Java: BFS

/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* ArrayList<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null)
return null; HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
LinkedList<UndirectedGraphNode> stack = new LinkedList<UndirectedGraphNode>();
UndirectedGraphNode head = new UndirectedGraphNode(node.label);
hm.put(node, head);
stack.push(node); while(!stack.isEmpty()){
UndirectedGraphNode curnode = stack.pop();
for(UndirectedGraphNode aneighbor: curnode.neighbors){//check each neighbor
if(!hm.containsKey(aneighbor)){//if not visited,then push to stack
stack.push(aneighbor);
UndirectedGraphNode newneighbor = new UndirectedGraphNode(aneighbor.label);
hm.put(aneighbor, newneighbor);
} hm.get(curnode).neighbors.add(hm.get(aneighbor));
}
} return head;
}
}

Java: BFS

/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* ArrayList<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
UndirectedGraphNode head = new UndirectedGraphNode(node.label);
hm.put(node, head);
queue.add(node); while (!queue.isEmpty()) {
UndirectedGraphNode currentNode = queue.remove();
for (UndirectedGraphNode neighbor : currentNode.neighbors) {
if (!hm.containsKey(neighbor)) {
queue.add(neighbor);
UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
hm.put(neighbor, newNeighbor);
}
hm.get(currentNode).neighbors.add(hm.get(neighbor));
}
} return head;
}
}

Python: DFS

class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = [] class Solution:
def cloneGraph(self, node):
def dfs(input, map):
if input in map:
return map[input]
output = UndirectedGraphNode(input.label)
map[input] = output
for neighbor in input.neighbors:
output.neighbors.append(dfs(neighbor, map))
return output if node == None: return None
return dfs(node, {})

Python: BFS

class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = [] class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if node is None:
return None
cloned_node = UndirectedGraphNode(node.label)
cloned, queue = {node:cloned_node}, [node] while queue:
current = queue.pop()
for neighbor in current.neighbors:
if neighbor not in cloned:
queue.append(neighbor)
cloned_neighbor = UndirectedGraphNode(neighbor.label)
cloned[neighbor] = cloned_neighbor
cloned[current].neighbors.append(cloned[neighbor])
return cloned[node]

C++:DFS

class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return NULL;
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> ht;
stack<UndirectedGraphNode*> s;
s.push(node);
ht[node] = new UndirectedGraphNode(node->label); while(!s.empty()) {
UndirectedGraphNode *p1 = s.top(), *p2 = ht[p1];
s.pop(); for(int i=0; i<p1->neighbors.size(); i++) {
UndirectedGraphNode *nb = p1->neighbors[i];
if(ht.count(nb)) {
p2->neighbors.push_back(ht[nb]);
}
else {
UndirectedGraphNode *temp = new UndirectedGraphNode(nb->label);
p2->neighbors.push_back(temp);
ht[nb] = temp;
s.push(nb);
}
}
} return ht[node];
}
};

C++: BFS

class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return NULL;
UndirectedGraphNode *p1 = node;
UndirectedGraphNode *p2 = new UndirectedGraphNode(node->label);
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> ht;
queue<UndirectedGraphNode*> q;
q.push(node);
ht[node] = p2; while(!q.empty()) {
p1 = q.front();
p2 = ht[p1];
q.pop();
for(int i=0; i<p1->neighbors.size(); i++) {
UndirectedGraphNode *nb = p1->neighbors[i];
if(ht.count(nb)) {
p2->neighbors.push_back(ht[nb]);
}
else {
UndirectedGraphNode *temp = new UndirectedGraphNode(nb->label);
p2->neighbors.push_back(temp);
ht[nb] = temp;
q.push(nb);
}
}
} return ht[node];
}
};

相似题目:

[LeetCode] 138. Copy List with Random Pointer 拷贝带随机指针的链表

All LeetCode Questions List 题目汇总

  

  

[LeetCode] 133. Clone Graph 克隆无向图的更多相关文章

  1. [leetcode]133. Clone Graph 克隆图

    题目 给定一个无向图的节点,克隆能克隆的一切 思路 1--2 | 3--5 以上图为例, node    neighbor 1         2, 3 2         1 3         1 ...

  2. [LeetCode] Clone Graph 克隆无向图

    Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph ...

  3. leetcode 133. Clone Graph ----- java

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...

  4. Java for LeetCode 133 Clone Graph

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...

  5. Leetcode#133 Clone Graph

    原题地址 方法I,DFS 一边遍历一边复制 借助辅助map保存已经复制好了的节点 对于原图中每个节点,如果已经复制过了,直接返回新节点的地址,如果没复制过,则复制并加入map中,接着依次递归复制其兄弟 ...

  6. 133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表

    133. Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of it ...

  7. 【LeetCode】133. Clone Graph (3 solutions)

    Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...

  8. [Leetcode Week3]Clone Graph

    Clone Graph题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/clone-graph/description/ Description Clon ...

  9. 133. Clone Graph (3 solutions)——无向无环图复制

    Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...

随机推荐

  1. Django创建管理员账号

    python manage.py createsuperuser 创建一个管理员账号 输入账号:admin 输入邮箱:123456789@qq.com 输入密码:test123456 二次确认 pyt ...

  2. Linux centos通过安装lszrz用CRT实现与Windows互相传文件

    本经验均在CentOSrelease6.7(Final)下操作,如知识有欠缺之处 欢迎批评指正: lrzsz是一个搭配SecureCRT使用的在linux和windows之间上传下载工具. 1 2 3 ...

  3. 关于srping的AOP事务管理问题,自定义切面是否导致事务控制失效

    applicationContext.xml: <!-- 方法调用时间记录 --> <bean id="methodExecuteTime" class=&quo ...

  4. NumPy的Linalg线性代数库探究

    1.矩阵的行列式 from numpy import * A=mat([[1,2,4,5,7],[9,12,11,8,2],[6,4,3,2,1],[9,1,3,4,5],[0,2,3,4,1]]) ...

  5. JQ js 对数组的操作

    1.数组的创建 var arrayObj = new Array(); //创建一个数组 var arrayObj = new Array([size]); //创建一个数组并指定长度,注意不是上限, ...

  6. 合并K个有序链表

    方法一:采用归并的思想将链表两两合并,再将两两合并后的链表做同样的操作直到合并为只有一个新的链表为止. 归类的时间复杂度是O(logn),合并两个链表的时间复杂度是O(n),则总的时间复杂度大概是O( ...

  7. 题解 UVa11609

    题目大意 给定一个正整数 \(n\),请求出所有小于 \(n\) 人的团队如果选出一个人作为队长的不同的方案数(假定这些人两两不相同)对 \(10^9+7\)取模的结果. 分析 即求 \[\sum^n ...

  8. KMP + BZOJ 4974 [Lydsy1708月赛]字符串大师

    KMP 重点:失配nxtnxtnxt数组 意义:nxt[i]nxt[i]nxt[i]表示在[0,i−1][0,i-1][0,i−1]内最长相同前后缀的长度 图示: 此时nxt[i]=jnxt[i]=j ...

  9. 10、Hadoop组件启动方式和SSH无密码登陆

    启动方式 一.各个组件逐一启动 hdfs: hadoop-daemon.sh start|stop namenode|datanode|secondnode yarn: yarn-demon.sh s ...

  10. BZOJ 4919: [Lydsy1706月赛]大根堆 set启发式合并

    这个和 bzoj 5469 几乎是同一道题,但是这里给出另一种做法. 你发现你要求的是一个树上 LIS,而序列上的 LIS 有一个特别神奇的 $O(n\log n) $ 做法. 就是维护一个单调递增的 ...