[Java] Leetcode 133. Clone Graph [Search #7]

preview_player
Показать описание
In this video, I'm going to show you how to solve Leetcode 133. Clone Graph which is related to Search.

Here’s a quick rundown of what you’re about to learn:

Course Contents
(0:00 ​) Question Walkthrough
(1:51) Solution Explain
(7:18) Code

In the end, you’ll have a really good understanding on how to solve Leetcode 133. Clone Graph and questions that are similar to this Search.

Рекомендации по теме
Комментарии
Автор

class Solution {
Map<Node, Node> table = new HashMap<>();

public Node cloneGraph(Node node) {
//Base case
if(node == null) return null;
//Define a queue
Queue<Node> queue = new LinkedList<>();

//Define a visited set to keep track visited nodes

Set<Node> 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<Node> 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);



//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;
}
}

EricProgramming
Автор

Thank you, Eric, your video and demo are very clear and helpful. :D!!

annabellesun
Автор

your search playlist has one video hidden what question was that?

chaitanyasharma
welcome to shbcf.ru