[leetcode]Q133Clone Graph
克隆图记住:一个map一个queue,照葫芦画瓢BFS
找到一个节点就画一个对应的新的,用map对应,然后添加邻居,记录邻居到queue
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node==null) return node; UndirectedGraphNode res = new UndirectedGraphNode(node.label); Queue<UndirectedGraphNode> queue = new LinkedList<>(); Map<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<>(); queue.offer(node); map.put(node,res); while (!queue.isEmpty()){ UndirectedGraphNode cur = queue.poll(); List<UndirectedGraphNode> neighbors = cur.neighbors; for (UndirectedGraphNode neighbor : neighbors) { if (!map.containsKey(neighbor)){ UndirectedGraphNode newNode = new UndirectedGraphNode(neighbor.label); queue.offer(neighbor); //在旧图中每遍历到一个节点,就在map中给新图申请一个对应的内存 map.put(neighbor,newNode); } //根据旧图中的位置为新图添加邻居 map.get(cur).neighbors.add(map.get(neighbor)); } } return res; }