带权 有向 图 邻接矩阵 建立 插入 删除

#include<bits/stdc++.h>
using namespace std;
//带权有向用邻接矩阵存储的图
const int maxNodeNum=10;//最大顶点数

typedef struct agraph{//图的结构体
    int nodeNum;//顶点数
    int edgeNum;//边数
    int biao[maxNodeNum][maxNodeNum];//邻接矩阵,存储的是有向边的权值,不连接则为0
}agraph;

agraph* init_graph(agraph* ingraph)//初始化图
{
    memset(ingraph->biao,0,sizeof(ingraph->biao));
    return ingraph;
}

agraph* creat_graph(int n)//建立新图并初始化,输入的参数n是顶点数
{
    agraph* newgraph=new agraph();
    init_graph(newgraph);
    newgraph->nodeNum=n;
    newgraph->edgeNum=0;
    return newgraph;
}

void show_graph(agraph* ingraph)//输出这个图
{
    int nodeNum=ingraph->nodeNum;
    for(int i=0;i<nodeNum;i++)
    {
        for(int j=0;j<nodeNum;j++)
        {
            printf("%d ",ingraph->biao[i][j]);
        }
        printf("\n");
    }
}

int insertEdge_graph(agraph* ingraph,int x,int y,int weight)//插入带权有向边,参数分别是:图的指针、边的起始点、边的终点、边的权值(范围是不为0的整数) 返回值0、1、2,1为正常执行
{
    if((x>ingraph->nodeNum)||(y>ingraph->nodeNum)||(x<=0)||(y<=0))//超出范围,错误,返回2
    {
        return 2;
    }
    else{
        x-=1;y-=1;//将xy调整到数组对应坐标
        if(ingraph->biao[x][y]!=0)//值不为0说明已经有边了,错误,返回0
        {
            return 0;
        }
        else if (ingraph->biao[x][y]==0)//正常插入
        {
            ingraph->biao[x][y]=weight;
            ingraph->edgeNum++;
            return 1;
        }
    }
}
int deleteEdge_graph(agraph* ingraph,int x,int y)//删除边,参数分别是:图的指针、边的起始点、边的终点 返回值0、1、2,1为正常执行
{
    if((x>ingraph->nodeNum)||(y>ingraph->nodeNum)||(x<=0)||(y<=0))//超出范围,错误,返回2
    {
        return 2;
    }
    else{
        x-=1;y-=1;//将xy调整到数组对应坐标
        if(ingraph->biao[x][y]==0)//值为0说明没有边,错误,返回0
        {
            return 0;
        }
        else if (ingraph->biao[x][y]!=0)//正常删除
        {
            ingraph->biao[x][y]=0;
            ingraph->edgeNum--;
            return 1;
        }
    }
}
int main()
{
    agraph* graph1=creat_graph(3);
    show_graph(graph1);
    insertEdge_graph(graph1,1,1,5);
    insertEdge_graph(graph1,2,1,-3);
    show_graph(graph1);
    cout<<graph1->edgeNum<<endl;
    deleteEdge_graph(graph1,1,1);
    show_graph(graph1);
    cout<<graph1->edgeNum<<endl;
    return 0;
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值