码迷,mamicode.com
首页 > 其他好文 > 详细

图与搜索总结

时间:2019-08-22 10:45:07      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:图片   ack   inf   搜索   技术   pre   get   init   turn   

技术图片

技术图片

 

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;

    Node() {}

    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/
//BFS
class Solution {
public:
    Node* cloneGraph(Node* node) {
        if(node == NULL)
            return NULL;
        
        //use bfs to get all nodes
        vector<Node*> nodes = bfs(node);
        
        unordered_map<Node*, Node*> mp;
        
        // copy nodes
        for(auto nod : nodes){
            Node* clone=new Node(nod->val);   // Node* clone=new Node(nod->val,vector<Node*>());
            mp[nod] = clone;
        }
        
        //copy neighbors/edges
        for(auto nod : nodes){
            Node* newNode = mp[nod];
            for(auto neighbor : nod->neighbors){
                Node* new_neigh = mp[neighbor];
                newNode->neighbors.push_back(new_neigh);
            }
        }
        
        return mp[node];
    }
    
    vector<Node*> bfs(Node* node){
        // use queue to implement bfs
        unordered_set<Node*> visited;
        queue<Node*> q;
        vector<Node*> nodes;
        
        q.push(node);
        visited.insert(node);
        nodes.push_back(node);
        
        while(!q.empty()){
            Node* cur = q.front();
            q.pop();
            for(auto neigh : cur->neighbors){
                //已经遍历过
                if(visited.find(neigh) != visited.end())
                    continue;
                
                //未遍历过
                q.push(neigh);
                visited.insert(neigh);
                nodes.push_back(neigh);
            }
        }
        return nodes;
    }
};

 

BFS 时间复杂度:O(边数 + 点数)

 

图与搜索总结

标签:图片   ack   inf   搜索   技术   pre   get   init   turn   

原文地址:https://www.cnblogs.com/Bella2017/p/11392660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!