基础图论基础 2017/04/20

Posted zhangwanying

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基础图论基础 2017/04/20相关的知识,希望对你有一定的参考价值。

 用临接链表表示一张图, 可以给图加边, 可以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 }
View Code

 

以上是关于基础图论基础 2017/04/20的主要内容,如果未能解决你的问题,请参考以下文章

基础图论3

图论基础——邻接链表存图+拓扑排序

图论算法零基础最小生成树学习与总结

动态规划综合+图论基础

图论基础知识.

机器学习|数学基础Mathematics for Machine Learning系列之图论:匹配的概念