leetcode 133. Clone Graph 图遍历BFS + 避免循环
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 node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
这道题考查的是图的遍历,可以使用BFS或者DFS,不过要避免循环。
代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
/*class UndirectedGraphNode
{
int label;
List<UndirectedGraphNode> neighbors;
UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
};
*/
/*
* 这个题主要的注意就是使用map映射结点信息
* */
public class Solution
{
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node)
{
if(node==null)
return null;
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
map.put(node, newNode);
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.add(node);
while(queue.isEmpty()==false)
{
UndirectedGraphNode top = queue.poll();
List<UndirectedGraphNode> list = top.neighbors;
for(int i=0;i<list.size();i++)
{
UndirectedGraphNode one = list.get(i);
if(map.containsKey(one)==false)
{
UndirectedGraphNode tmp = new UndirectedGraphNode(one.label);
map.put(one, tmp);
//只有新建的需要加入queue,否者不需要,避免图中的环
queue.add(one);
}
map.get(top).neighbors.add(map.get(one));
}
}
return newNode;
}
}
还没有评论,来说两句吧...