Skip to content

Latest commit

ย 

History

History
35 lines (27 loc) ยท 1016 Bytes

File metadata and controls

35 lines (27 loc) ยท 1016 Bytes
class Solution {
    public Node cloneGraph(Node node) {
        return cloneGraph(new HashMap<>(), node);
    }

    private Node cloneGraph(Map<Integer, Node> map, Node node) {
        if(node == null) {
            return null;
        }

        if (map.containsKey(node.val)) {
            return map.get(node.val);
        }

        Node copy = new Node(node.val);
        map.put(node.val, copy);

        for (int i = 0; i < node.neighbors.size(); i++) {
            Node neighborNode = node.neighbors.get(i);
            copy.neighbors.add(map.getOrDefault(neighborNode.val, cloneGraph(map, node.neighbors.get(i))));
        }

        return copy;
    }
}

TC, SC

node(vertex)์˜ ์ˆ˜๋ฅผ V, edge์˜ ์ˆ˜๋ฅผ E ๋ผ๊ณ  ํ•˜์˜€์„ ๋•Œ ๊ฐ ๋…ธ๋“œ ๋งˆ๋‹ค edge์˜ ์ˆ˜๋งŒํผ ๋ฐ˜๋ณต์„ ํ•ด์•ผํ•œ๋‹ค. ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(V + E) ์ด๋‹ค. ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” O(V)์ด๋‹ค.