Skip to content

Instantly share code, notes, and snippets.

@mashiro
Created October 20, 2020 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mashiro/2b0a70bbc422472bb77980dd81a2cd05 to your computer and use it in GitHub Desktop.
Save mashiro/2b0a70bbc422472bb77980dd81a2cd05 to your computer and use it in GitHub Desktop.
# Definition for a Node.
# class Node
# attr_accessor :val, :neighbors
# def initialize(val = 0, neighbors = nil)
# @val = val
# neighbors = [] if neighbors.nil?
# @neighbors = neighbors
# end
# end
# @param {Node} node
# @return {Node}
def cloneGraph(node)
_cloneGraph(node, {})
end
def _cloneGraph(node, memo)
return nil if node.nil?
return memo[node.val] if memo.include? node.val
new_node = memo[node.val] = Node.new node.val
new_node.neighbors = node.neighbors.map { |n| _cloneGraph(n, memo) }
new_node
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment