LeetCode 133: Clone Graph

link

We can piggyback on DFS to clone the graph. We copy a node when we explore it.

Note, if a shallow reference of u exists in the map, we should grab that reference and deepen it. Otherwise, an earlier node storing u‘s reference in its neighbors list, will not be able to access the updated, deeper u.

Time: \mathcal{O}( |V|+|E| ), space: \mathcal{O}( |V| ).

"""
# Definition for a Node.
class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []
"""

from typing import Optional
class Solution:
    def copy_node(self, u, map):
        map[u] = map.get(u, Node(u.val))
        for v in u.neighbors:
            map[v] = map.get(v, Node(v.val))
            map[u].neighbors.append(map[v])

    def explore(self, u, map, visited):
        self.copy_node(u, map)
        visited.add(u)
        for v in u.neighbors:
            if v in visited:
                continue
            self.explore(v, map, visited)

    def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
        if not node:
            return None
        map = {}
        self.explore(node, map, set())
        return map[node]

Leave a comment