用临接链表表示一张图, 可以给图加边, 可以bfs
1 #include <iostream> 2 #include <list> 3 #include <vector> 4 #include <queue> 5 6 using namespace std; 7 8 void createGraph(const int& N) { 9 return; 10 } 11 12 void addEdge(const int fromNode, const int endNode, vector<list<int>>& graph) { 13 graph[fromNode].push_back(endNode); 14 } 15 16 17 void bfs(vector<list<int>>& graph, int start) { 18 const int N = graph.size(); 19 vector<int> ans; 20 queue<int> q; 21 vector<bool> visit(N, false); 22 q.push(start); 23 visit[start] = true; 24 while(!q.empty()) { 25 int cur = q.front(); 26 q.pop(); 27 ans.push_back(cur); 28 for (auto iter = graph[cur].begin(); iter != graph[cur].end(); ++iter) { 29 if (!visit[*iter]) { 30 q.push(*iter); 31 visit[*iter] = true; 32 } 33 } 34 } 35 for (auto ele : ans) { 36 cout << ele << " "; 37 } 38 } 39 40 void print_graph(vector<list<int>>& graph) { 41 const int N = graph.size(); 42 for (auto i = 0; i < N; ++i) { 43 const int M = graph[i].size(); 44 int j = 0; 45 for (auto iter = graph[i].begin(); iter != graph[i].end(); ++iter, ++j) { 46 cout << *iter ; 47 if (j == M - 1) { 48 cout << endl; 49 } else { 50 cout << " -> "; 51 } 52 } 53 } 54 return; 55 } 56 57 58 int main() { 59 60 const int N = 4; 61 vector<list<int>> graph(N, list<int>()); 62 for (auto i = 0; i < N; ++i) { 63 graph[i].push_back(i); 64 } 65 addEdge(0, 1, graph); 66 addEdge(0, 2, graph); 67 addEdge(1, 2, graph); 68 addEdge(2, 0, graph); 69 addEdge(2, 3, graph); 70 addEdge(3, 3, graph); 71 72 print_graph(graph); 73 74 bfs(graph, 1); 75 76 return 0; 77 }
dfs 基础练习
http://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1