zoukankan      html  css  js  c++  java
  • 数据结构之连通图算法

    #include<stdio.h>
    #include<string.h>
    #include<math.h>
    #define MAXN 110
    
    using namespace std;
    
    typedef char VertexType;
    typedef int EdgeType;
    int k;
    int s[MAXN];
    int vis[MAXN];
    typedef struct
    {
        char vexes[MAXN];
        int maps[MAXN][MAXN];
        int numVexes, numEdge;
    }MGraph;
    ///用邻接矩阵创建图
    void CreateGraph(MGraph &G)
    {
        int u, v;
        printf("输入顶点数和边数:");
        scanf("%d %d", &G.numVexes, &G.numEdge);
    
        getchar();
        for(int i=0; i<G.numVexes; i++)
            scanf("%c", &G.vexes[i]);
    
        for(int i=0; i<G.numVexes; i++)
            for(int j=0; j<G.numVexes; j++)
                G.maps[i][j]=0;
    
        for(int i=0; i<G.numEdge; i++)
        {
            scanf("%d %d", &u, &v);
            G.maps[u][v]=G.maps[v][u]=1;
        }
    }
    ///从顶点i起深度优先遍历
    void DFS(MGraph G, int u)
    {
        vis[u]=1;
        putchar(G.vexes[u]);
        s[k++]=u;
        for(int i=0; i<G.numVexes; i++)
            if(G.maps[u][i]&&!vis[i])
                DFS(G, i);
    }
    ///深度优先遍历
    int DFSM(MGraph G)
    {
        int cnt=0;
        memset(vis, 0, sizeof(vis));
        for(int i=0; i<G.numVexes; i++)
        {
            if(!vis[i])
            {
                k=0;
                memset(s, 0, sizeof(s));
                cnt++;
                DFS(G, i);
                printf(":");
                for(int z=0; z<k; z++)
                    printf(" %d", s[z]);
                printf("--%d
    ", k);
            }
        }
        return cnt;
    }
    ///求连通分量的个数
    int Count_Conn(MGraph G)
    {
        int cnt=0;
        memset(vis, 0, sizeof(vis));
        for(int v=0; v<G.numVexes; v++)
        {
            if(!vis[v])
            {
                cnt++;
                DFS(G, v);
            }
        }
        return cnt;
    }
    int main()
    {
        MGraph G;
        CreateGraph(G);
        int Count=DFSM(G);
        printf("%d
    ", Count);
        return 0;
    }
    /*
    样例输入:
    13 13 ABCDEFGHIJKLM 0 1 0 2 0 5 0 11 1 12 3 4 6 7 6 8 6 10 9 11 9 12 11 12 7 10 样例输出: ABMJLCF:0 1 12 9 11 2 5--7 DE:3 4--2 GHKI:6 7 10 8-- 4 3 */
  • 相关阅读:
    SQL Sever语言 存储过程及触发器
    计蒜客 挑战难题 移除数组中的重复元素
    projecteuler Sum square difference
    码农谷 求前N项之和
    projecteuler Smallest multiple
    计蒜客 挑战难题 寻找插入位置
    Largest palindrome product
    计蒜客 挑战难题 元素移除
    码农谷 球从M米高度自由下落第N次落地时反弹的高度
    挑战难题 奇怪的国家
  • 原文地址:https://www.cnblogs.com/w-y-1/p/8034515.html
Copyright © 2011-2022 走看看