1、题目描述
2、问题分析
要遍历图,然后标记没有被复制的节点。
3、代码
1 class Solution { 2 3 private: 4 unordered_map<Node*, Node*> m; 5 6 public: 7 Node* cloneGraph(Node* node) { 8 if (node == NULL) 9 return NULL; 10 11 Node *copy = new Node(node->val, {}); 12 queue<Node*> q; 13 m[node] = copy; 14 q.push(node); 15 16 while (!q.empty()) { 17 Node *cur = q.front(); 18 q.pop(); 19 20 for(Node* neighbor : cur->neighbors) { 21 if (m.find(neighbor) == m.end()) { 22 m[neighbor] = new Node(neighbor->val, {}); 23 q.push(neighbor); 24 } 25 m[cur]->neighbors.push_back(m[neighbor]); 26 27 } 28 } 29 return copy; 30 } 31 };