图与搜索总结-DFS, BFS leetcode 133.

 

/*
// 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(边数 + 点数)

 

 

 

 

 

 

 

 

 

 参考链接:

(word ladder)

https://www.youtube.com/watch?v=70l1rGhJ-8A&list=PLgkTb_uYkq5f6mI52NZv68QTb6Ui7omWX&index=9

(word ladder II)

https://www.youtube.com/watch?v=X84Huebakeg

 

 用BFS来创建一个从startWord 到 endWord 有最短路径的图;再使用DFS来遍历这个图,求出所有的路径。如下图:

 

 若在wordList找到了变换后的单词,不能像 word Ladder一样,将这个单词从wordList中删除,因为上一题是找出一条路径即可;而这道题需要找出所有路径,如下图,tex被找到之后不能删除,因为ted还需要用它。故这一层可以有重复的。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2019-08-22 09:54  爱学英语的程序媛  阅读(214)  评论(0编辑  收藏  举报