leetcode || 133、Clone Graph
來源:程序員人生 發布時間:2015-05-21 08:10:33 閱讀次數:3295次
problem:
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
/
\_/
Hide Tags
Depth-first Search Breadth-first
Search Graph
題意:復制圖(結構和數據不變,要新建節點)
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:
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> record;
if(node == NULL)
return node;
stack<UndirectedGraphNode*> queue;
queue.push(node);
while(!queue.empty()) {
UndirectedGraphNode *nextNode = queue.top();
queue.pop();
if(!record.count(nextNode)) {
UndirectedGraphNode *newNode = new UndirectedGraphNode(nextNode->label);
record[nextNode] = newNode;
}
for(int i = nextNode->neighbors.size()⑴; i >= 0 ; i --) {
UndirectedGraphNode *childNode = nextNode->neighbors[i];
if(!record.count(childNode)) {
UndirectedGraphNode *newNode = new UndirectedGraphNode(childNode->label);
record[childNode] = newNode;
queue.push(childNode);
}
record[nextNode]->neighbors.push_back(record[childNode]);
}
}
return record[node];
}
};
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈