1. Clone Graph
BFS:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 typedef UndirectedGraphNode UGNode; 4 UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) { 5 if (node == NULL) { 6 return NULL; 7 } 8 vector<UGNode*> nodes; 9 unordered_map<UGNode*, UGNode*> umap; 10 11 //clone nodes only 12 nodes.push_back(node); 13 umap[node] = new UGNode(node->label); 14 int start = 0; 15 while (start < nodes.size()) { 16 UGNode* tmp = nodes[start]; 17 start++; 18 for (int i = 0; i < tmp->neighbors.size(); i++) { 19 if (umap.count(tmp->neighbors[i]) == 0) { 20 nodes.push_back(tmp->neighbors[i]); 21 umap[tmp->neighbors[i]] = new UGNode(tmp->neighbors[i]->label); 22 } 23 } 24 } 25 26 //clone neighbors only 27 for (int i = 0; i < nodes.size(); i++) { 28 UGNode* newNode = umap[nodes[i]]; 29 for (int j = 0; j < nodes[i]->neighbors.size(); j++) { 30 newNode->neighbors.push_back(umap[nodes[i]->neighbors[j]]); 31 } 32 } 33 return umap[node]; 34 } 35 };
DFS:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 typedef UndirectedGraphNode UGNode; 4 UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) { 5 if (node == NULL) { 6 return NULL; 7 } 8 return dfs(node); 9 } 10 11 UGNode* dfs(UGNode* node) { 12 UGNode* p = new UGNode(node->label); 13 umap[p->label] = p; 14 for (int i = 0; i < node->neighbors.size(); i++) { 15 if (umap.count(node->neighbors[i]->label) == 0) { 16 p->neighbors.push_back(dfs(node->neighbors[i])); 17 } else { 18 p->neighbors.push_back(umap[node->neighbors[i]->label]); 19 } 20 } 21 return p; 22 } 23 private: 24 unordered_map<int, UGNode*> umap; 25 };
这里umap里的second存的都是copy后的图节点,不是原图。
图的邻接表DFS:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 struct VertexNode { 2 int data; 3 EdgeNode* next; 4 }; 5 6 struct EdgeNode { 7 int index; // 存储其对应的点的下标 8 EdgeNode* next; 9 }; 10 11 struct Graph { 12 VertexNode vexs[MAXVEX]; 13 int numVertex; 14 }; 15 16 vector<bool> visited; 17 18 void dfs(Graph* g, int i) { 19 visited[i] = 1; 20 print(g, i); 21 EdgeNode* p = g->vexs[i]->next; 22 while (p) { 23 if (!visited[p->index]) { 24 dfs(g, p->index); 25 } 26 p = p->next; 27 } 28 } 29 30 void dfsTraverse(Graph* g) { 31 for (int i = 0; i < g->numVertex; i++) { 32 if (!visited[i]) { 33 dfs(g, i); 34 } 35 } 36 }
图的邻接表BFS:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 void bfsTraverse(Graph* g) { 2 queue<int> q; 3 for (int i = 0; i < numVertex; i++) { 4 if (!visited[i]) { 5 visited[i] = 1; 6 print(g, i); 7 q.push(i); 8 while (!q.empty()) { 9 int j = q.top(); 10 q.pop(); 11 EdgeNode* p = g->vexs[j].next; 12 while (p) { 13 if (!visited[p->index]) { 14 visited[p->index] = 1; 15 print(g, p->index); 16 q.push(p->index); 17 } 18 p = p->next; 19 } 20 } 21 } 22 } 23 }