Advertisement
Guest User

Grokking #196

a guest
Nov 7th, 2021
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. class Solution {
  2.  
  3.   class Node {
  4.     public int val;
  5.     public List<Node> neighbors;
  6.     public Node() {
  7.         val = 0;
  8.         neighbors = new ArrayList<Node>();
  9.     }
  10.     public Node(int _val) {
  11.         val = _val;
  12.         neighbors = new ArrayList<Node>();
  13.     }
  14.     public Node(int _val, ArrayList<Node> _neighbors) {
  15.         val = _val;
  16.         neighbors = _neighbors;
  17.     }
  18.   }
  19.  
  20.   // store visited node, and cloned node
  21.   Map<Node, Node> visited;
  22.  
  23.   public Node cloneGraph(Node node) {
  24.     if (node == null) {
  25.       return null;
  26.     }
  27.    
  28.     visited = new HashMap<Node, Node>();
  29.        
  30.     dfsClone(node);
  31.      
  32.     return visited.get(node);
  33.   }
  34.  
  35.   private void dfsClone(Node at) {
  36.     if (visited.containsKey(at)) {
  37.       return;
  38.     }
  39.    
  40.     // clone current node and store mapping
  41.     Node cloned = new Node(at.val);
  42.     visited.put(at, cloned);
  43.    
  44.     // explore all neighbor nodes and clone
  45.     for (Node to : at.neighbors) {
  46.       dfsClone(to);
  47.      
  48.       // add cloned of neighbour node to current node's neighbors
  49.       cloned.neighbors.add(visited.get(to));
  50.     }
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement