难度:medium
说明:
对一个相互依赖的对象,进行一次深克隆,返回一个全新的对象。
问题链接:https://leetcode.com/problems/clone-graph/
输入案例:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]] Output: [[2,4],[1,3],[2,4],[1,3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).其实这个和spring的解决依赖循环一个意思,也跟 tow sum 一样的解决方法,使用一个 map 进行缓存,然后进行递归实例化未实例化的对象,再进行 neighbors 添加。
public class Solution { public Node cloneGraph(Node node) { if (node == null) { return node; } // 搞个缓存 HashMap<Integer, Node> cacheMap = new HashMap<Integer, Node>(); return clone(node, cacheMap); } public Node clone(Node node, HashMap<Integer, Node> cacheMap) { Node newNode = new Node(); newNode.val = node.val; newNode.neighbors = new ArrayList<>(); cacheMap.put(node.val, newNode); for(Node ne : node.neighbors) { if(cacheMap.containsKey(ne.val)) { newNode.neighbors.add(cacheMap.get(ne.val)); } else { Node one = clone(ne, cacheMap); // 递归逐个实例化 one.val = ne.val; newNode.neighbors.add(one); } } return newNode; } }
