zoukankan      html  css  js  c++  java
  • 从0开始 图论学习 广度优先搜索 链式前向星表示法

    广度搜索 - 链式前向星表示法

    writer:pprp

    分析:

    • 参数:当前节点的标号为bfs的参数
    • 注意:要另外开一个VIS数组进行涂色,涂过色的就不要再涂色了
    • head数组应该全置-1,VIS数组全置0
    • 遍历的时候利用到了queue进行操作,注意应该在qu.front()和qu.pop()的位置
    代码如下:
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <queue>
    //图的遍历
    using namespace std;
    const int maxn = 1000;
    int vv,ee;
    struct node
    {
        int to;
        int w;
        int next;
    };
    queue <int> qu;
    
    node edge[maxn];
    int head[maxn];
    bool vis[maxn];
    
    //顶点
    void bfs()
    {
        int x;
        while(!qu.empty())
        {
            x = qu.front();
            vis[x] = 1;
            cout << x << endl;
            for(int k = head[x]; k != -1; k = edge[k].next)
            {
                if(!vis[edge[k].to])
                {
                    qu.push(edge[k].to);
                }
            }
            qu.pop();
        }
    }
    
    int main()
    {
        freopen("in.txt","r",stdin);
        int x, y,z ;
        cin >> vv >> ee;
        memset(head,-1,sizeof(head));
        memset(vis,0,sizeof(vis));
        for(int i = 0 ; i < ee; i++)
        {
            cin >> x >> y >> z;
            edge[i].to = y;
            edge[i].w = z;
            edge[i].next = head[x];
            head[x] = i;
        }
        qu.push(0);
        bfs();
        return 0;
    }
    
    
  • 相关阅读:
    4.6--4.9
    4.表达式和运算符
    3.9--3.10
    3.8
    泛型(Generic)
    容器
    String,StringBuffer
    数组
    异常,自定义异常,异常重写
    多态,抽象类和抽象方法,接口
  • 原文地址:https://www.cnblogs.com/pprp/p/7788592.html
Copyright © 2011-2022 走看看