[LeetCode] 133. Clone Graph

思路:
这里两个思路, 第一个是DFS, 第二个是BFS. 大同小异, 都是要用一个哈希表, 哈希表第一项是原图的节点, 第二项是原图对应的新图的该节点. 哈希的好处是一能记录当前节点是否之前已经创造过新节点了, 二是维护了第二个图各节点之间的关系.

UndirectedGraphNode* dfs(unordered_map& hashmap, 
                            UndirectedGraphNode* node) {
    if (! node) return NULL;
    if (! hashmap.count(node)) {
        hashmap[node] = new UndirectedGraphNode(node->label);
        for (int i = 0; i < node->neighbors.size(); i++) 
            hashmap[node]->neighbors.push_back(dfs(hashmap, node->neighbors[i]));
    }
    return hashmap[node];
}

UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    unordered_map hashmap;
    return dfs(hashmap, node);
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    if (! node) return NULL;
    unordered_map hashmap;
    queue q;

    UndirectedGraphNode* new_node = new UndirectedGraphNode(node->label);
    hashmap[node] = new_node;
    q.push(node);

    while (! q.empty()) {
        UndirectedGraphNode* cur = q.front();
        q.pop();
        for (int i = 0; i < cur->neighbors.size(); i++) {
            UndirectedGraphNode* curNeighbor = cur->neighbors[i];
            if (! hashmap.count(curNeighbor)) {
                hashmap[curNeighbor] = new UndirectedGraphNode(curNeighbor->label);
                q.push(curNeighbor);
            }
            hashmap[cur]->neighbors.push_back(hashmap[curNeighbor]);
        }
    }

    return new_node;
}

你可能感兴趣的:(LeetCode,leetcode,dfs,bfs,图论)