LeetCode 133 Clone Graph
Deep copy of a connected undirected graph, and there are some similar problems like this like: clone a N-ary tree.
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {}
public Node(int _val,List<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
in order to clone the whole graph, you have to at least go through every node of the graph at least once.
so the ways to traverse every node in a graph are either DFS or BFS.
I prefer BFS. and the most common data structure in a graph problem is HashMap, which will helps us to keep track of all the nodes that is visited and helps us the construct the whole graph.
in order to solve this problem, we need a very clear mind on what’s the meaning of that hashmap(what does this k-v pair constructed)
class Solution {
//private HashMap<Node, Node> visited = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
HashMap<Node, Node> visited = new HashMap<Node, Node>();
Queue<Node> queue = new LinkedList<>();
queue.add(node);
visited.put(node, new Node(node.val, new ArrayList<>()));//old node and the deep copy of this node
while(!queue.isEmpty()) {
Node cur = queue.poll();
List<Node> neigs = cur.neighbors;
for (Node neig: neigs) {
//visited.get(cur).add(neig);
if (!visited.containsKey(neig)) {
visited.put(neig, new Node(neig.val, new ArrayList<>())); //make a copy of neig node
queue.add(neig);
}
visited.get(cur).neighbors.add(visited.get(neig)); //we get the cloned node of cur, and we add the copy of this neighbor to it's neighbors list
}
}
return visited.get(node);
}
}

浙公网安备 33010602011771号