【LeetCode】133. Clone Graph 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/clone-graph/
题目描述
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
Example:
Input:
{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}
Explanation:
Node 1's value is 1, and it has two neighbors: Node 2 and 4.
Node 2's value is 2, and it has two neighbors: Node 1 and 3.
Node 3's value is 3, and it has two neighbors: Node 2 and 4.
Node 4's value is 4, and it has two neighbors: Node 1 and 3.
Note:
- The number of nodes will be between 1 and 100.
- The undirected graph is a simple graph, which means no repeated edges and no self-loops in the graph.
- Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too.
- You must return the copy of the given node as a reference to the cloned graph.
题目大意
完全复制一个图结构。返回新的起始节点。
解题方法
DFS
这个题和138. Copy List with Random Pointer比较类似。至于图结构,我们可以使用DFS和BFS两种结构进行遍历。
一般的遍历只需要保存是否遍历过这个节点即可,但是由于这个题需要把neighboors对应复制过来。那么需要进行改进,改进的方式是把set改成dict,保存每个老节点对应的新节点是多少。在Python中,字典直接保存对象(指针)之间的映射。所以,我们直接把遍历过的对象和复制出来的对象一一对应即可。当我们遍历到一个新的节点的时候,需要判断这个节点是否在字典中出现过,如果出现过就把它对应的复制出来的对象放到其neighboors里,若没有出现过,那么就重新构造该节点,并把原节点和该节点放到字典中保存。
Python代码如下:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
"""
class Solution(object):
def cloneGraph(self, node):
"""
:type node: Node
:rtype: Node
"""
node_copy = self.dfs(node, dict())
return node_copy
def dfs(self, node, hashd):
if not node: return None
if node in hashd: return hashd[node]
node_copy = Node(node.val, [])
hashd[node] = node_copy
for n in node.neighbors:
n_copy = self.dfs(n, hashd)
if n_copy:
node_copy.neighbors.append(n_copy)
return node_copy
C++代码如下:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
if (!node) return nullptr;
if (m_.count(node))
return m_[node];
Node* node_copy = new Node(node->val, {});
m_[node] = node_copy;
for (Node* n : node->neighbors) {
node_copy->neighbors.push_back(cloneGraph(n));
}
return node_copy;
}
private:
unordered_map<Node*, Node*> m_;
};
BFS
这个题同样也可以使用BFS解决。方法也是使用了字典保存每一个对应关系。当新构造出一个节点之后,必须同时把它放到字典中保存,这个很重要。另外就是每遍历到一个节点时,都要把它的所有邻居放到队列中。
python代码如下:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
"""
class Solution(object):
def cloneGraph(self, node):
"""
:type node: Node
:rtype: Node
"""
que = collections.deque()
hashd = dict()
que.append(node)
node_copy = Node(node.val, [])
hashd[node] = node_copy
while que:
t = que.popleft()
if not t: continue
for n in t.neighbors:
if n not in hashd:
hashd[n] = Node(n.val, [])
que.append(n)
hashd[t].neighbors.append(hashd[n])
return node_copy
C++代码如下:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
queue<Node*> q;
q.push(node);
unordered_map<Node*, Node*> m_;
Node* node_copy = new Node(node->val, {});
m_[node] = node_copy;
while (!q.empty()) {
Node* t = q.front(); q.pop();
if (!t) continue;
for (Node* n : t->neighbors) {
if (!m_.count(n)) {
m_[n] = new Node(n->val, {});
q.push(n);
}
m_[t]->neighbors.push_back(m_[n]);
}
}
return node_copy;
}
};
日期
2019 年 3 月 9 日 —— 妇女节快乐
【LeetCode】133. Clone Graph 解题报告(Python & C++)的更多相关文章
- LeetCode: Clone Graph 解题报告
Clone GraphClone an undirected graph. Each node in the graph contains a label and a list of its neig ...
- [LeetCode] 133. Clone Graph 克隆无向图
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- 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 ...
- 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 ...
- [leetcode]133. Clone Graph 克隆图
题目 给定一个无向图的节点,克隆能克隆的一切 思路 1--2 | 3--5 以上图为例, node neighbor 1 2, 3 2 1 3 1 ...
- Leetcode#133 Clone Graph
原题地址 方法I,DFS 一边遍历一边复制 借助辅助map保存已经复制好了的节点 对于原图中每个节点,如果已经复制过了,直接返回新节点的地址,如果没复制过,则复制并加入map中,接着依次递归复制其兄弟 ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- 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 ...
随机推荐
- 43-Reverse Nodes in k-Group
Reverse Nodes in k-Group My Submissions QuestionEditorial Solution Total Accepted: 58690 Total Submi ...
- jsp的动态包含和静态包含
jsp的动态包含和静态包含 例如:提取一个公共的页面(top.jsp)到/WEB-INF/jsp/common/目录下 动态包含: 被包含的页面也会独立编译,生成字节码文件,一般包含页面信息频繁变化的 ...
- 学习java的第十五天
一.今日收获 1.完成了手册第二章没有验证完成的例题 2.预习了第三章的算法以及for语句与if语句的用法 二.今日难题 1.验证上出现问题,没有那么仔细. 2.第二章还有没有完全理解的问题 三.明日 ...
- Hadoop入门 常见错误及解决方案
常见错误及解决方案 目录 常见错误及解决方案 ResourceManager连接失败 root用户和ranan用户两个用户启动集群不统一 不识别主机名 DataNode和NameNode进程同时只能工 ...
- 日常Java 2021/9/23
练习使用Math.random函数,以及JOptionPane.showMessageDialog(null,"字符串","Results",JOptionPa ...
- 【leetcode】337. House Robber III
The thief has found himself a new place for his thievery again. There is only one entrance to this a ...
- oracle中的数组
Oracle中的数组分为固定数组和可变数组. 一.固定数组固定数组:在定义的时候预定义了数组的大小,在初始化数组时如果超出这个大小,会提示ORA-06532:超出小标超出限制!语法: T ...
- linux添加用户、权限
# useradd –d /usr/sam -m sam 此命令创建了一个用户sam,其中-d和-m选项用来为登录名sam产生一个主目录/usr/sam(/usr为默认的用户主目录所在的父目录). 假 ...
- tomcat 之 httpd session stiky
# 注释中心主机 [root@nginx ~]# vim /etc/httpd/conf/httpd.conf #DocumentRoot "/var/www/html" #:配置 ...
- 编译安装nginx 1.16
准备源码包,并解压,创建nginx用户 [root@slave-master ~]# tar xf nginx-1.16.0.tar.gz [root@slave-master ~]# useradd ...