#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;
}
带权 有向 图 邻接矩阵 建立 插入 删除
于 2022-11-12 22:07:59 首次发布