class Solution { Map table = new HashMap(); public Node cloneGraph(Node node) { //Base case if(node == null) return null; //Define a queue Queue queue = new LinkedList(); //Define a visited set to keep track visited nodes Set visited = new HashSet(); //Add current node to the queue queue.add(node); //BFS while(!queue.isEmpty()){ //Take the first from queue Node first = queue.poll(); if(visited.contains(first)) continue; //Mark this node as visited visited.add(first); //If this node is not create in the table, create it Node newFirst = getNewNode(first); List neighbors = first.neighbors; //Iterate all the connect nodes from this node for(Node cur : neighbors){ //For each node, if not created, then create it in the table Node newCurNode = getNewNode(cur); newFirst.neighbors.add(newCurNode); //If this node is not visited, add to the queue if(!visited.contains(cur)){ queue.add(cur); } } } return table.get(node); } private Node getNewNode(Node node){ if(table.containsKey(node)) return table.get(node); int val = node.val; Node newNode = new Node(val); table.put(node, newNode); return newNode; } }
@gordonlichunfu2 жыл бұрын
Clear, and to the point!
@annabellesun47192 жыл бұрын
Thank you, Eric, your video and demo are very clear and helpful. :D!!
@EricProgramming2 жыл бұрын
Glad it was helpful!
@raj_kundalia Жыл бұрын
thank you!
@chaitanyasharma62702 жыл бұрын
your search playlist has one video hidden what question was that?