|
| 1 | +// https://leetcode.com/problems/clone-graph |
| 2 | +// T: O(n) |
| 3 | +// S: O(n) |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.HashSet; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.Set; |
| 11 | + |
| 12 | +public class CloneGraph { |
| 13 | + private static final class Node { |
| 14 | + public int val; |
| 15 | + public List<Node> neighbors; |
| 16 | + |
| 17 | + public Node() { |
| 18 | + val = 0; |
| 19 | + neighbors = new ArrayList<>(); |
| 20 | + } |
| 21 | + |
| 22 | + public Node(int val) { |
| 23 | + this.val = val; |
| 24 | + neighbors = new ArrayList<>(); |
| 25 | + } |
| 26 | + |
| 27 | + public Node(int val, ArrayList<Node> neighbors) { |
| 28 | + this.val = val; |
| 29 | + this.neighbors = neighbors; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public Node cloneGraph(Node node) { |
| 34 | + if (node == null) return null; |
| 35 | + final Map<Integer, Node> graph = new HashMap<>(); |
| 36 | + cloneGraph(node, new HashSet<>(), graph); |
| 37 | + return graph.get(node.val); |
| 38 | + } |
| 39 | + |
| 40 | + private void cloneGraph(Node node, Set<Integer> visited, Map<Integer, Node> newGraph) { |
| 41 | + if (node == null) return; |
| 42 | + if (visited.contains(node.val)) return; |
| 43 | + visited.add(node.val); |
| 44 | + |
| 45 | + Node current = getNode(newGraph, node.val); |
| 46 | + for (Node adjacent : node.neighbors) { |
| 47 | + Node newNeighbour = getNode(newGraph, adjacent.val); |
| 48 | + current.neighbors.add(newNeighbour); |
| 49 | + cloneGraph(adjacent, visited, newGraph); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + private Node getNode(Map<Integer, Node> graph, int value) { |
| 54 | + if (graph.containsKey(value)) return graph.get(value); |
| 55 | + Node node = new Node(value); |
| 56 | + graph.put(value, node); |
| 57 | + return node; |
| 58 | + } |
| 59 | +} |
0 commit comments