Clona un gráfico no dirigido. Cada nodo del gráfico contiene una etiqueta y una lista de sus vecinos.
Solución Java 1 – DFS
HashMap<Node, Node> map = new HashMap<>(); public Node cloneGraph(Node node) { map.put(node, new Node(node.val, new ArrayList<>())); for(Node neighbor: node.neighbors){ if(map.containsKey(neighbor)){ map.get(node).neighbors.add(map.get(neighbor)); }else{ map.get(node).neighbors.add(cloneGraph(neighbor)); } } return map.get(node); } |
Solución Java 2 – BFS
public Node cloneGraph(Node node) { Map<Node, Node> map = new HashMap<>(); Queue<Node> queue = new ArrayDeque<>(); queue.offer(node); map.put(node, new Node(node.val, new ArrayList<>())); while (!queue.isEmpty()) { Node h = queue.poll(); for (Node neighbor : h.neighbors) { if (!map.containsKey(neighbor)) { map.put(neighbor, new Node(neighbor.val, new ArrayList<>())); queue.offer(neighbor); } map.get(h).neighbors.add(map.get(neighbor)); } } return map.get(node); } |