标签:图片 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