- 需要掌握图的表示方法,图分为两种常见表示:邻接表,邻接矩阵。主要有一个neighbors的vector来存所有邻居的信息
- 遇到图的题,要遍历图,一般选择BFS,因为宽度优先遍历可以用队列实现,不会发生栈溢出的情况
- 遇到图的题,要遍历图,需要一个Hashmap,因为图可能有环,尤其对于无向图,为了避免二次访问,Hashmap非常重要
- 需要记忆,c++中Hashmap用unordered_map来表示
- 需要记忆,mapping.find(x) == mapping.end()来判断是否已存储了某值
- 克隆图,便是遍历一遍,生成点和边,注意可以一遍生成没必要遍历两遍。每次while都是生成neighbors的点和front的之间的边。
class Solution {
public:
UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) {
if (node == NULL) {
return NULL;
}
queue<UndirectedGraphNode *> q;
q.push(node);
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> mapping;
mapping[node] = new UndirectedGraphNode(node->label);
while (!q.empty()) {
UndirectedGraphNode * head = q.front();
q.pop();
for (UndirectedGraphNode * neighbor: head->neighbors) {
if (mapping.find(neighbor) == mapping.end()) {
mapping[neighbor] = new UndirectedGraphNode(neighbor->label);
q.push(neighbor);
}
mapping[head]->neighbors.push_back(mapping[neighbor]);
}
}
return mapping[node];
}
};