Clone an undirected graph. Each node in the graph contains a
label and a list of its neighbors.OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph
{0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by
#.- First node is labeled as
0. Connect node0to both nodes1and2. - Second node is labeled as
1. Connect node1to node2. - Third node is labeled as
2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
public class Solution {
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
// write your code here
if(node == null) return null;
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.offer(node);
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(node, newNode);
while(!queue.isEmpty()){
UndirectedGraphNode cur = queue.poll();
ArrayList<UndirectedGraphNode> neighbors = cur.neighbors;
for(UndirectedGraphNode n : neighbors){
if(map.containsKey(n)){
map.get(cur).neighbors.add(map.get(n));
} else {
UndirectedGraphNode temp = new UndirectedGraphNode(n.label);
map.put(n, temp);
map.get(cur).neighbors.add(temp);
queue.offer(n);
}
}
}
return newNode;
}
}
Yes
No comments:
Post a Comment