Clone Graph
Clone an undirected graph. Each node in the graph contains a
label and a list of its neighbors.Analysis:
A typical graph problem, either DFS or BFS does the trick.
Solution:
class Solution {
public:
UndirectedGraphNode *DFS(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode*> &visited)
{
UndirectedGraphNode *ret = new UndirectedGraphNode(node->label);
visited[node->label] = ret;
for(int i = 0; i < node->neighbors.size(); i++)
{
UndirectedGraphNode *temp = node->neighbors[i];
if(visited[temp->label])
{
ret->neighbors.push_back(visited[temp->label]);
}
else
{
ret->neighbors.push_back(DFS(node->neighbors[i], visited));
}
}
return ret;
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
UndirectedGraphNode *ret;
unordered_map<int, UndirectedGraphNode*> visited;
ret = DFS(node, visited);
return ret;
}
};
No comments:
Post a Comment