用数组存储和创建图结构

问题:定义结构体要分配空间,这个不知为什么?

有很长时间没写数据结构了,忙,也不知忙什么。。。下面创建的是无向图。主要是记得图的结构体的定义,我刚开始没想起来,查了资料才弄明白的。

代码:

#include <iostream>
#include <cstdlib>
using namespace std;
#define MAXVEX 20
typedef struct map
{
    char vex[MAXVEX];
    int arrMap[MAXVEX][MAXVEX];
    int numvexs,numedges;
}mapNode;
 
int getPos(mapNode *g,char v)    //返回顶点的位置
{
    int i=0;
    for(i=0;i<g->numvexs;i++)
    {
        if(g->vex[i]==v)
        {
            break;
        }
    }
    if(i>=g->numvexs)
        return -1;
    return i;
}
 
void  createGraph(mapNode* &g)
{
    char p,q;
    int m,n;
    cout<<"please input the nums of the vexs and edges:";
    cin>>g->numvexs;
    cin>>g->numedges;
    getchar();
    cout<<"input the infor of the vexs:"<<endl;
    for(int i=0;i<g->numvexs;i++)
    {
        cin>>g->vex[i];
    }
 
    for(int k=0;k<g->numvexs;k++)            //初始化图矩阵
    {
        for(int r=0;r<g->numvexs;r++)
        {
            g->arrMap[k][r]=0;
        }
    }
 
    for(int j=0;j<g->numedges;j++)
    {
        cout<<"please input two vexs:";
        cin>>p>>q;
        m=getPos(g,p);
        n=getPos(g,q);
        if(m==-1||n==-1)
        {
            cout<<"输入错误"<<endl;
            return;
        }
        else
        {
            g->arrMap[m][n]=1;
            g->arrMap[n][m]=1;
        }
    }
}
 
void playMap(mapNode *g)
{
    for(int i=0;i<g->numvexs;i++)
    {
        for(int j=0;j<g->numvexs;j++)
        {
            cout<<g->arrMap[i][j]<<"  ";
        }
        cout<<endl;
    }
    cout<<endl;
}
 
int main()
{
    mapNode *mn=NULL;
    mn=(mapNode *)malloc(sizeof(struct map));
    if(!mn)
        return -1;
    cout<<"创建图:"<<endl;
    createGraph(mn);
    cout<<"输出图:"<<endl;
    playMap(mn);
    return 0;
}

 运行结果:

posted @   xshang  阅读(399)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示