🤖
Data Structures and Algorithms
  • CS Theory And Problems
  • Big O
    • Big O Notation
  • Algorithms
    • Binary Search
    • Breadth First Search (BFS)
    • Depth First Search (DFS)
    • Dynamic Programming
    • Kadane's Algorithm
    • Kahn's Algorithm
    • Quickselect
    • Recursion
    • Sorting Algorithms
    • Sliding Window
  • Data Structures
    • Binary Heap
    • Graph
    • Linked List
    • Trees
  • Problems
    • LeetCode
      • 1. Two Sum
      • 3. Longest Substring Without Repeating Characters
      • 5. Longest Palindromic Substring
      • 11. Container With Most Water
      • 15. 3 Sum
      • 19. Remove Nth Node From End of List
      • 20. Valid Parentheses
      • 33. Search in Rotated Sorted Array
      • 49. Group Anagrams
      • 53. Maximum Subarray
      • 55. Jump Game
      • 56. Merge Intervals
      • 76. Minimum Window Substring
      • 98. Validate Binary Search Tree
      • 105. Construct Binary Tree from Preorder and Inorder Traversal
      • 121. Best Time to Buy and Sell Stock
      • 133. Clone Graph
      • 141. Linked List Cycle
      • 152. Maximum Product Subarray
      • 153. Find Minimum in Rotated Sorted Array
      • 200. Number of Islands
      • 206. Reverse Linked List
      • 207. Course Schedule
      • 217. Contains Duplicate
      • 226. Invert Binary Tree
      • 238. Product of Array Except Self
      • 242. Valid Anagram
      • 297. Serialize and Deserialize Binary Tree
      • 347. Top K Frequent Elements
      • 417. Pacific Atlantic Water Flow
      • 424. Longest Repeating Character Replacement
      • 435. Non-overlapping Intervals
      • 647. Palindromic Substrings
Powered by GitBook
On this page
  • Description
  • Solution
  1. Problems
  2. LeetCode

133. Clone Graph

Description

See: https://leetcode.com/problems/clone-graph/

Given a graph, return a deep copy of it.

Solution

This problem is a graph traversal problem. I used BFS traversal to solve it. It uses the standard algorithm, but with the following changes:

  • an extra variable, current_clone, is used to store the copied node. When the current_node neighbors are traversed the standard check is done to see if the neighbor has been visited or not. If it has not been added then a new Node is created with the value. This is the copied value. In both cases the neighbor is added to the current_clone neighbors list.

  • The visited hash value stores a copy of a Node. In the standard algorithm it is simply stores True. This hash stores the deep copy values.

"""
# 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 []
"""

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        if node is None:
            return node
        
        # note to self could also do queue = deque([node]) to condense the following two lines
        queue = deque()
        queue.append(node)
        
        # note: the visited hash creates a new Node as the value. This is the copy the question is asking for
        visited = {node.val: Node(node.val)}       
        while queue:
            current_node = queue.popleft()
            current_clone = visited[current_node.val]
            for neighbour in current_node.neighbors:
                if neighbour.val not in visited:
                    # Note: a new Node is created with the neighbour's val. This is the copy mechanism
                    visited[neighbour.val] = Node(neighbour.val)
                    queue.append(neighbour)
                # Note: The node that is appended is the one from the visited hash. This is the copy value
                current_clone.neighbors.append(visited[neighbour.val])
        # Note: return from the visited hash, as it holds the copied graph
        return visited[node.val]    
Previous121. Best Time to Buy and Sell StockNext141. Linked List Cycle

Last updated 3 years ago