大体题意:
这个题目看了许久 才发现就是一道水题,他就是给你一个无向图,建图的方式都不用你管,他是用vector 保存的!
在给你一个新的点,克隆出这个图来!第一次做leetcode,搞了半天。。
思路:
BFS或者DFS都行 只要能遍历一遍所有的点就好了!
这个图有自环, 加个vis判断是否重复访问即可!
因为是克隆图嘛,可以建立一个unordered_map <UndirectedGraphNode*,UndirectedGraphNode*> mp;
来一个原点和新点的映射!
详细见代码:
BFS版:
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL)return NULL;
unordered_map <UndirectedGraphNode*,UndirectedGraphNode*> mp;
unordered_map <UndirectedGraphNode*,bool> vis;
queue<UndirectedGraphNode*>q;
mp.clear();
vis.clear();
while(!q.empty()) q.pop();
q.push(node);
vis[node] = false;
while(!q.empty()){
UndirectedGraphNode* u = q.front(); q.pop();
if (vis[u])continue;
vis[u] = true;
if (!mp.count(u)) mp[u] = new UndirectedGraphNode (u->label);
for (int i = 0; i < u->neighbors.size(); ++i){
UndirectedGraphNode* v = u->neighbors[i];
UndirectedGraphNode * tmp;
if (!mp.count(v)){
tmp = new UndirectedGraphNode (v->label);
mp[v] = tmp;
}else tmp = mp[v];
q.push(v);
mp[u]->neighbors.push_back(tmp);
}
}
return mp[node];
}
};
DFS版:
class Solution {
public:
unordered_map<UndirectedGraphNode* ,UndirectedGraphNode* >mp;
unordered_map<UndirectedGraphNode* ,bool >vis;
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL)return NULL;
mp.clear();
vis.clear();
dfs(node);
return mp[node];
}
void dfs(UndirectedGraphNode *node){
vis[node] = true;
if (!mp.count(node)) mp[node] = new UndirectedGraphNode(node->label);
UndirectedGraphNode* u = mp[node];
for (int i = 0; i < node->neighbors.size(); ++i){
UndirectedGraphNode *v = node->neighbors[i];
if (vis[v]) continue;
if (!mp.count(v)) mp[v] = new UndirectedGraphNode (v->label);
dfs(v);
}
for (int i = 0; i < node->neighbors.size(); ++i){
UndirectedGraphNode *v = node->neighbors[i];
u->neighbors.push_back(mp[v]);
}
}
};
133. Clone Graph
- Total Accepted: 85949
- Total Submissions: 344554
- Difficulty: Medium
- Contributors: Admin
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 node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
C++