当前位置:网站首页>有向图深拷贝
有向图深拷贝
2022-06-12 21:25:00 【围城_危城】
无向图node结点
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
方式一,深度优先遍历算法拷贝:
class Solution {
//存储访问过的结点及其拷贝的结点
private HashMap <Node, Node> visited = new HashMap <> ();
public Node cloneGraph(Node node) {
if (node == null) {
return node;
}
// 如果该节点已经被访问过了,则直接从哈希表中取出对应的克隆节点返回
if (visited.containsKey(node)) {
return visited.get(node);
}
// 克隆节点,注意到为了深拷贝我们不会克隆它的邻居的列表
Node cloneNode = new Node(node.val, new ArrayList());
// 哈希表存储
visited.put(node, cloneNode);
// 遍历该节点的邻居并更新克隆节点的邻居列表
for (Node neighbor: node.neighbors) {
cloneNode.neighbors.add(cloneGraph(neighbor));
}
return cloneNode;
}
}
方式二、广度优先遍历算法拷贝:
class Solution {
public Node cloneGraph(Node node) {
if (node == null) {
return node;
}
HashMap<Node, Node> visited = new HashMap();
// 将题目给定的节点添加到队列
LinkedList<Node> queue = new LinkedList<Node> ();
queue.add(node);
// 克隆第一个节点并存储到哈希表中
visited.put(node, new Node(node.val, new ArrayList()));
// 广度优先搜索
while (!queue.isEmpty()) {
// 取出队列的头节点
Node n = queue.remove();
// 遍历该节点的邻居
for (Node neighbor: n.neighbors) {
if (!visited.containsKey(neighbor)) {
// 如果没有被访问过,就克隆并存储在哈希表中
visited.put(neighbor, new Node(neighbor.val, new ArrayList()));
// 将邻居节点加入队列中
queue.add(neighbor);
}
// 更新当前节点的邻居列表
visited.get(n).neighbors.add(visited.get(neighbor));
}
}
return visited.get(node);
}
}
边栏推荐
猜你喜欢

leetcode:207. Class Schedule Card

Test basis: unit test

GPU giant NVIDIA suffered a "devastating" network attack, and the number one malware shut down its botnet infrastructure | global network security hotspot on February 28

ASCII 码对照表

字符串基础知识

Mxnet record IO details

Introduction to the characteristics of balancer decentralized exchange market capitalization robot

Teamwork collaboration application experience sharing | community essay solicitation

makefile 的ifeq,filter,strip 简单使用

Integrated monitoring solution for power environment of small and medium-sized computer rooms
随机推荐
Insert sort
Delphi XE7的蓝牙 Bluetooth
remote: Support for password authentication was removed on August 13, 2021
重排数列练习题
A high-value MySQL management tool
Data visualization - histogram
The service did not report any errors MySQL
Principales étapes de la collecte des ordures à Zgc
#886 Possible Bipartition
CUDA out of memory
RestTemplate的@LoadBalance注解
GNS安装与配置
二分查找
Two sentences to clarify JS throttling and anti shake
Scope and scope chain
Understanding of functions
What are the disadvantages of bone conduction earphones? Analysis of advantages and disadvantages of bone conduction earphones
Structure knowledge points all in
Leetcode: 210. Programme II
Market trend report, technical innovation and market forecast of hydraulic chain hoist in China