• 图论 用广搜搜邻接矩阵


    用广搜搜邻接矩阵

    只是从某一点开始搜,如果是遍历全图的话就每个顶点挨个搜一遍

    #include<stdio.h>
    #include<string.h>
    #include<string>
    #include<iostream>
    #include<algorithm>
    #include<queue>
    #define inf 65535
    using namespace std;
    typedef struct mygraph
    {
        int ver[1000];
        int arc[100][100];
        int num_ver,num_edge;
    } Graph;
    int vis[100];
    void create(Graph *G)//邻接矩阵建图
    {
        int i,j,k;
        scanf("%d%d",&G->num_ver,&G->num_edge);//输入节点数和边数
        for(i=0; i<G->num_ver; i++)//输入边集
            scanf("%d",&G->ver[i]);
        for(i=0; i<G->num_ver; i++)//权值初始化
        {
            for(j=0; j<G->num_edge; j++)
                G->arc[i][j]=inf;
        }
        int a,b,c;
        for(i=0; i<G->num_edge; i++)//输入边集
        {
            scanf("%d%d%d",&a,&b,&c);
            G->arc[a][b]=c;
            G->arc[b][a]=c;
        }
    }
    
    queue<int>q;
    void bfs(Graph *g,int x)//广搜
    {
        int i,tmp,tmp1,tmp2;
        while(!q.empty())q.pop();
        q.push(x);
        vis[x]=1;
        while(!q.empty())
        {
            tmp=q.front();
            printf("%d",tmp);
            q.pop();
            for(i=0; i<g->num_ver; i++)
            {
                if(!vis[i]&&g->arc[tmp][i]!=inf)
                {
                    q.push(i);
                    vis[i]=1;
                }
            }
        }
    }
    
    int main()
    {
        int i,j,k;
        Graph myG;
        create(&myG);
        memset(vis,0,sizeof(vis));
        bfs(&myG,0);
        printf("
    ");
    
    //    for(i=0; i<myG.num_ver; i++)//打印邻接矩阵
    //    {
    //        for(j=0; j<myG.num_ver; j++)
    //            printf("%5d ",myG.arc[i][j]);
    //        printf("
    ");
    //    }
    
    
    
        return 0;
    }
    
    /*
    5 6
    0 1 2 3 4
    0 1 9
    0 2 2
    0 4 6
    1 2 3
    2 3 5
    3 4 1
    */

    测试数据中5  6代表节点数为5,边数为,6,下面是结点名0 1 2 3 4  下面几行中分别为为 弧尾(边的起点),弧首(边的终点),和边的权值


  • 相关阅读:
    (转)浅析epoll-为何多路复用I/O要使用epoll
    (转)C++对象的内存布局
    (转)C++ 虚函数表解析
    VS2008文件编码格式修改
    ubuntu与windows相关配置内容
    (转)windows宿主机,ubuntu虚拟机下的上网设置(有线网络和无线网络)
    第10章 名字控制
    php 代码重用
    php 变量
    php in_array 和 str_replace
  • 原文地址:https://www.cnblogs.com/hjch0708/p/7554834.html
Copyright © 2020-2023  润新知