第六章学习小结

列出连通集:

#include <cstdio>

#define N 15

void ListComponentsWithDFS();
void ListComponentsWithBFS();
void DFS(int V);
void BFS(int V);
void InitVisit(void);

int n;
bool Visited[N];
int G[N][N] = {0};

int main()
{
    int E;

    scanf("%d%d", &n, &E);
    for (int i = 0; i < E; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        G[b][a] = G[a][b] = 1;
    }
    ListComponentsWithDFS();
    InitVisit();
    ListComponentsWithBFS();

    return 0;
}

void ListComponentsWithDFS()
{
    for (int V = 0; V < n; V++)
        if (!Visited[V])
        {
            printf("{ ");
            DFS(V);
            printf("}\n");
        }
}

void ListComponentsWithBFS()
{
    for (int V = 0; V < n; V++)
        if (!Visited[V])
        {
            printf("{ ");
            BFS(V);
            printf("}\n");
        }
}

void DFS(int V)
{
    Visited[V] = true;
    printf("%d ", V);
    for (int i = 0; i < n; i++)
    {
        if (G[V][i] && !Visited[i])
            DFS(i);
    }
}

void BFS(int V)
{
    const int MAX_SIZE = 100;
    int Queue[MAX_SIZE];
    int first = -1, last = -1;

    Queue[++last] = V;      //入队
    Visited[V] = true;
    while (first < last)    //当队不为空时
    {
        int F = Queue[++first];     //出队
        printf("%d ", F);
        for (int i = 0; i < n; i++)
        {
            if (G[F][i] && !Visited[i])
            {
                Queue[++last] = i;      //入队
                Visited[i] = true;
            }
        }
    }
}

void InitVisit()
{
    for (int i = 0; i < N; i++)
        Visited[i] = false;
}

第六章学习了图的有关存储结构和遍历,图一个区别于线性表和树结构的又一大数据结构,一个图就是一些顶点的集合,这些顶点通过一系列连接,边可以有权重。图的遍历包括深度优先搜索和广度优先搜索。而最小生成树在我们生活中应用十分广泛,可以解决城市路线规划问题,生产流程问题等等,老师为我们讲解了普里姆算法和克鲁斯卡算法,并根据算法画出二叉树,希望掌握了这些能在星期一的考试有所突破- -。

posted @ 2019-05-19 22:07  海豆S  阅读(131)  评论(1编辑  收藏  举报