Make a deep copy of an undirected graph, there could be cycles in the original graph.
Assumptions
/* * class GraphNode { * public int key; * public List<GraphNode> neighbors; * public GraphNode(int key) { * this.key = key; * this.neighbors = new ArrayList<GraphNode>(); * } * } */ public class Solution { public List<GraphNode> copy(List<GraphNode> graph) { // Write your solution here. Map<GraphNode, GraphNode> map = new HashMap<>(); for (GraphNode node : graph) { if (!map.containsKey(node)) { map.put(node, new GraphNode(node.key)); } dfs(node, map); } return new ArrayList<>(map.values()); } private void dfs(GraphNode node, Map<GraphNode, GraphNode> map) { GraphNode newNode = map.get(node); for (GraphNode gNode : node.neighbors) { if (!map.containsKey(gNode)) { map.put(gNode, new GraphNode(gNode.key)); } newNode.neighbors.add(map.get(gNode)); } } }
[Algo] 132. Deep Copy Undirected Graph
原文:https://www.cnblogs.com/xuanlu/p/12366061.html