标签:des style blog http io ar color os sp
复制一个无向图。图的结构时有一个label,一个vector存和他想接的节点。可以自循环,就是vector中可以存在自己。例如:
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:
1 / / 0 --- 2 / \_/
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (!node) return node; //if ((node -> neighbors).size() == 0) return node; queue<UndirectedGraphNode *> que, que2; que.push(node); UndirectedGraphNode *root = new UndirectedGraphNode(node -> label), *tmp, *subnode, *tmp2; unordered_set<UndirectedGraphNode*> uset; que2.push(root); while(!que.empty()) { tmp = que.front(); tmp2 = que2.front(); uset.insert(tmp); que.pop(); que2.pop(); for (int i = 0; i < tmp -> neighbors.size(); ++i) { if (tmp -> neighbors[i] == tmp) subnode = tmp2; else subnode = new UndirectedGraphNode(tmp -> neighbors[i] -> label); tmp2 -> neighbors.push_back(subnode); if (uset.count(tmp -> neighbors[i]) == 0) { que.push(tmp -> neighbors[i]); que2.push(subnode); } } } return root; } };
但是超时了,可能最近感冒脑子不灵活了哎。
不知道为什么上面用两个队列会超时啊。换成map的映射的话就不会超时:
unordered_map(UndirectedGraphNode *, UndirectedGraphNode *) copied; 指key对应的node是否在value对应的node中复制。
因为是BFS要用一个que来存自己已经复制,但是他的neighbors还没有复制的节点。那么初始化que就要push一个node,而copied[node]就是赋值为node->label对应的新节点。
然后根据que是否为空处理。
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (!node) return node; unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> copied; queue<UndirectedGraphNode *> que; que.push(node); copied[node] = new UndirectedGraphNode(node -> label); while(!que.empty()) { UndirectedGraphNode *cur = que.front(); que.pop(); for (int i = 0; i < cur -> neighbors.size(); ++i) { if (copied.count(cur->neighbors[i])) copied[cur] -> neighbors.push_back(copied[cur -> neighbors[i]]); else { UndirectedGraphNode *new_node = new UndirectedGraphNode(cur -> neighbors[i] -> label); copied[cur -> neighbors[i]] = new_node; copied[cur] -> neighbors.push_back(new_node); que.push(cur -> neighbors[i]); } } } return copied[node]; } };
这有DFS
标签:des style blog http io ar color os sp
原文地址:http://www.cnblogs.com/higerzhang/p/4156373.html