• 【基础】图论基础 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

     dfs 基础练习

    http://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1

  • 相关阅读:
    Ext.dataGroupingStore/JsonStore/SimpleStore
    转:LinQ操作汇总(From CSharpSamples)
    XSLT教程 比较全的
    使用ASP.Net Forms模式实现WebService身份验证
    关于DataRow的RowState和RowVersion
    C#日志工具汇总
    转 Using log4net,
    js//初始话日期
    两个数据库表的连接 查询
    ExtJS入门之三 查询
  • 原文地址:https://www.cnblogs.com/zhangwanying/p/6740341.html
Copyright © 2020-2023  润新知