133. Clone Graph#
1class Solution {
2 Map<Node, Node> map = new HashMap<>();
3
4 public Node cloneGraph(Node node) {
5 if (node == null) {
6 return node;
7 }
8
9 if (!map.containsKey(node)) {
10 map.put(node, new Node(node.val));
11
12 for (Node neighbor : node.neighbors) {
13 map.get(node).neighbors.add(cloneGraph(neighbor));
14 }
15 }
16
17 return map.get(node);
18 }
19}