publicclassM133_cloneGraph{ public Node cloneGraph(Node node){ Node[] nodes = new Node[100]; if (node == null) returnnull; if (node.neighbors == null) returnnew Node(); if (node.neighbors.size() == 0) returnnew Node(1, new ArrayList<>()); nodes = dfs(node, new Node(node.val, new ArrayList<>()), nodes); return nodes[1]; }
public Node[] dfs(Node olds, Node newnode, Node[] nodes) { nodes[olds.val] = newnode; int i = 0; for (Node node1 : olds.neighbors) { if (nodes[node1.val] != null) { newnode.neighbors.add(nodes[node1.val]); i++; continue; } newnode.neighbors.add(new Node(node1.val, new ArrayList<>())); nodes = dfs(node1, newnode.neighbors.get(i), nodes); i++; } return nodes; } }