problem:
Clone an undirected graph. Each node in the graph contains a label
and
a list of its neighbors
.
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 #
.
0
.
Connect node 0
to both nodes 1
and 2
.1
.
Connect node 1
to node 2
.2
.
Connect node 2
to node 2
(itself),
thus forming a self-cycle.Visually, the graph looks like the following:
thinking:
(1)要新建图的各个节点,保持邻接关系不变。
(2)采取unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> 存储原节点和新节点。而不是unordered_map<int, UndirectedGraphNode*>,
效力要高很多
(3)采取BFS思想,将原节点的邻接节点全部入栈或堆栈,遍历节点。
(4)map中查找key是不是存在可以调用find(),也能够调用count(),后者效力更高
(5)提交没通过,结果不正确:
Input:{0,1,5#1,2,5#2,3#3,4,4#4,5,5#5}
Output:{0,5,1#1,5,2#2,3#3,4,4#4,5,5#5}
Expected:{0,1,5#1,2,5#2,3#3,4,4#4,5,5#5}
其实,结果是正确的,由于对无向图,节点出现的顺序不影响图的结构,只能说这个验证程序只验证了1种结果
code: