【数据结构与算法】假设图采用邻接表存储,判断一个未知顶点个数和边数的无向连通图G是否是棵树

题目

  Qestion:设计一个算法,判断一个未知顶点个数和边数的无向连通图G是否是棵树,假设图采用邻接表存储。若是树,返回true;否则返回 false。
(用图1和图2验证作业题2算法的正确性)
在这里插入图片描述在这里插入图片描述


图一图二的邻接表结构

在这里插入图片描述


运行结果以及其解释

由结果可知图一为无向连通图,图二不为无向连通图

图一的运行结果

在这里插入图片描述

图二的运行结果

在这里插入图片描述


数据结构与定义

#include <stdio.h>
#include <iostream>

using namespace std;

#define MaxSize 20 // 最大顶点的个数
struct Node
{
    int weight;
    int index;
    struct Node *next;
};
struct HNode
{
    char nodeData;
    struct Node *next;
};
struct Graph
{
    int vertexNum;
    int arcNum;
    bool isDireted;
    HNode verList[MaxSize];
};

主控函数

bool IsTree(Graph G){ }

bool IsTree(Graph G)
{
    bool IsVisited[MaxSize]; // 记录每个顶点是否被访问过
    int NodeCnt = 0;         // 记录访问的顶点个数
    int ArcCnt = 0;          // 记录边的个数
    bool IsTree = false;     // 判断图G是否为树
    DFS(G, G.verList[0], 0, IsVisited, NodeCnt, ArcCnt);
    if ((!G.isDireted) && (ArcCnt / 2 == NodeCnt - 1)) // 因为是无向图所以边要除以2
    {
        IsTree = true; // 无向连通图G中恰好有n-1条边
    }
    return IsTree;
}

核心函数

void DFS(Graph G, HNode V, int i, bool IsVisited[], int &NodeCnt, int &ArcCnt){ }

void DFS(Graph G, HNode V, int i, bool IsVisited[], int &NodeCnt, int &ArcCnt)
{
    if (!IsVisited[i])
    {
        IsVisited[i] = true;
        NodeCnt++;
        Node *tmp = V.next; // tmp指向HNode的第一个Node结点
        if (tmp == nullptr) // HNode的next为空
        {
            DFS(G, G.verList[i + 1], i + 1, IsVisited, NodeCnt, ArcCnt);
        }
        else // HNode的next不为空
        {
            do
            {
                if (IsArcExist(G.verList[i].nodeData, G.verList[tmp->index].nodeData, G)) // 判断是否有该边长
                {
                    ArcCnt++;
                }
                DFS(G, G.verList[tmp->index], tmp->index, IsVisited, NodeCnt, ArcCnt); // 递归到下一层
                tmp = tmp->next;                                                       // tmp向后移
            } while (tmp != nullptr);                                                  // 当tmp不为nullptr时一直进行DFS并且tmp后移
        }
    }
}

完整代码

#include <stdio.h>
#include <iostream>

using namespace std;

#define MaxSize 20 // 最大顶点的个数
struct Node
{
    int weight;
    int index;
    struct Node *next;
};
struct HNode
{
    char nodeData;
    struct Node *next;
};
struct Graph
{
    int vertexNum;
    int arcNum;
    bool isDireted;
    HNode verList[MaxSize];
};

int Locate(char c, Graph G)
{
    int index = -1;
    for (int i = 0; i < G.vertexNum; i++)
    {
        if (G.verList[i].nodeData == c)
        {
            index = i;
        }
    }
    return index;
}

void InsertVex(Graph &G, char v)
{
    G.verList[G.vertexNum].nodeData = v;
    G.verList[G.vertexNum].next = nullptr;
    G.vertexNum++;
}

void InsertArc(Graph &G, char tail, char head)
{
    int TailIndex, HeadIndex;
    TailIndex = Locate(tail, G);
    HeadIndex = Locate(head, G);
    if (HeadIndex == -1 || TailIndex == -1) // 输入的弧头或者弧尾不存在
    {
        return;
    }
    // 无论G为有向图还是无向图
    Node *newNode = new Node;
    newNode->next = G.verList[TailIndex].next; // 头插法插入到邻接表中
    newNode->index = HeadIndex;
    G.verList[TailIndex].next = newNode;
    if (!G.isDireted) // G为无向图
    {
        Node *newNode = new Node;
        newNode->next = G.verList[HeadIndex].next; // 头插法插入到邻接表中
        newNode->index = TailIndex;
        G.verList[HeadIndex].next = newNode;
    }
}

void CreateGraph(Graph &G)
{
    cin >> G.vertexNum >> G.arcNum; // 输入顶点数和边数
    cin >> G.isDireted;             // 输入是否为有向图
    if (G.vertexNum > MaxSize)
    {
        return;
    }
    // 初始化顶点列表
    for (int i = 0; i < G.vertexNum; i++)
    {
        cin >> G.verList[i].nodeData;
        G.verList[i].next = nullptr;
    }
    // 依次输入各边的信息
    for (int j = 0; j < G.arcNum; j++)
    {
        char ArcHead, ArcTail;
        cin >> ArcTail >> ArcHead;
        InsertArc(G, ArcTail, ArcHead);
    }
}

bool IsArcExist(char a, char b, Graph G)
{
    int AIndex, BIndex; // 找到弧头和弧尾的数组下标
    for (int i = 0; i < G.vertexNum; i++)
    {
        if (G.verList[i].nodeData == a)
        {
            AIndex = i;
            continue;
        }
        if (G.verList[i].nodeData == b)
        {
            BIndex = i;
            continue;
        }
    }
    Node *tmp = G.verList[AIndex].next;
    while (tmp != nullptr)
    {
        if (tmp->index == BIndex)
        {
            return true;
        }
        tmp = tmp->next;
    }
    return false;
}

void DFS(Graph G, HNode V, int i, bool IsVisited[], int &NodeCnt, int &ArcCnt)
{
    if (!IsVisited[i])
    {
        IsVisited[i] = true;
        NodeCnt++;
        Node *tmp = V.next; // tmp指向HNode的第一个Node结点
        if (tmp == nullptr) // HNode的next为空
        {
            DFS(G, G.verList[i + 1], i + 1, IsVisited, NodeCnt, ArcCnt);
        }
        else // HNode的next不为空
        {
            do
            {
                if (IsArcExist(G.verList[i].nodeData, G.verList[tmp->index].nodeData, G)) // 判断是否有该边长
                {
                    ArcCnt++;
                }
                DFS(G, G.verList[tmp->index], tmp->index, IsVisited, NodeCnt, ArcCnt); // 递归到下一层
                tmp = tmp->next;                                                       // tmp向后移
            } while (tmp != nullptr);                                                  // 当tmp不为nullptr时一直进行DFS并且tmp后移
        }
    }
}

bool IsTree(Graph G)
{
    bool IsVisited[MaxSize]; // 记录每个顶点是否被访问过
    int NodeCnt = 0;         // 记录访问的顶点个数
    int ArcCnt = 0;          // 记录边的个数
    bool IsTree = false;     // 判断图G是否为树
    DFS(G, G.verList[0], 0, IsVisited, NodeCnt, ArcCnt);
    if ((!G.isDireted) && (ArcCnt / 2 == NodeCnt - 1)) // 因为是无向图所以边要除以2
    {
        IsTree = true; // 无向连通图G中恰好有n-1条边
    }
    return IsTree;
}

int main()
{
    Graph G;
    CreateGraph(G);
    bool res = IsTree(G);
    cout << res << endl;
    return 0;
}


结束语

  因为是算法小菜,所以提供的方法和思路可能不是很好,请多多包涵~如果有疑问欢迎大家留言讨论,你如果觉得这篇文章对你有帮助可以给我一个免费的赞吗?我们之间的交流是我最大的动力!

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,对于您的问题,我可以提供以下 C 语言代码来实现: ```c #include <stdio.h> #include <stdlib.h> // 定义邻接表结点 typedef struct node { int vertex; struct node* next; } Node; // 定义邻接表 typedef struct adj_list { Node* head; } AdjList; // 定义结构 typedef struct graph { int vertices; AdjList* array; } Graph; // 初始化邻接表 Node* create_node(int vertex) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->vertex = vertex; newNode->next = NULL; return newNode; } // 创建 Graph* create_graph(int vertices) { Graph* graph = (Graph*)malloc(sizeof(Graph)); graph->vertices = vertices; graph->array = (AdjList*)malloc(vertices * sizeof(AdjList)); int i; for (i = 0; i < vertices; ++i) { graph->array[i].head = NULL; } return graph; } // 添加边 void add_edge(Graph* graph, int src, int dest) { // 添加边(src -> dest) Node* newNode = create_node(dest); newNode->next = graph->array[src].head; graph->array[src].head = newNode; // 添加边(dest -> src),由于无向图的存在,需要添加两条边 newNode = create_node(src); newNode->next = graph->array[dest].head; graph->array[dest].head = newNode; } // 深度优先搜索 void dfs(int vertex, int* visited, Graph* graph) { visited[vertex] = 1; printf("%d ", vertex); // 遍历顶点的每个邻接顶点 Node* adj_vertex = graph->array[vertex].head; while (adj_vertex != NULL) { if (!visited[adj_vertex->vertex]) { dfs(adj_vertex->vertex, visited, graph); } adj_vertex = adj_vertex->next; } } // 输出 G 的一颗深度优先生成 void dfs_spanning_tree(Graph* graph) { int* visited = (int*)malloc(graph->vertices * sizeof(int)); int i; for (i = 0; i < graph->vertices; ++i) { visited[i] = 0; } // 从第一个顶点开始遍历 dfs(0, visited, graph); } // 主函数 int main() { int vertices = 5; Graph* graph = create_graph(vertices); add_edge(graph, 0, 1); add_edge(graph, 0, 2); add_edge(graph, 1, 2); add_edge(graph, 1, 3); add_edge(graph, 2, 3); add_edge(graph, 3, 4); dfs_spanning_tree(graph); return 0; } ``` 希望这可以帮助您解决问题!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hiddenSharp429

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值