C++有向图以邻接矩阵存储,试编写图的基本运算(删除一条边、求某个顶点的出度)

题目:

有向图以邻接矩阵存储,试编写图的基本运算(删除一条边、求某个顶点的出度)

实现代码:


#include <iostream>
#include <stdio.h>
using namespace std;
#define INF 32767				
#define	MAXV 100				
typedef char InfoType;


typedef struct
{	int no;						
	InfoType info;				
} VertexType;					

typedef struct
{	int edges[MAXV][MAXV];		
	int n, e;					
	VertexType vexs[MAXV];		
} MatGraph;						

void CreateMat(MatGraph &g, int A[MAXV][MAXV], int n, int e) 
{	int i, j;
	g.n = n;
	g.e = e;
	for (i = 0; i < g.n; i++)
		for (j = 0; j < g.n; j++)
		{	if (i == j)
			{	g.edges[i][j] = 0;
			}
			else if (A[i][j] == 0 && i < j)
			{	g.edges[i][j] = INF;
				g.edges[j][i] = INF;
			}
			else if (i < j)
			{	g.edges[i][j] = A[i][j];
				g.edges[j][i] = A[i][j];
			}
		}

}

void DispMat(MatGraph g)	
{	int i, j;
	for (i = 0; i < g.n; i++)
	{	for (j = 0; j < g.n; j++)
			if (g.edges[i][j] != INF)
				printf("\t%d", g.edges[i][j]);
			else
				printf("\t%s", "∞");
		printf("\n");
	}
}

void DelArc(MatGraph &g, int u, int v)
{	if (g.edges[u][v] == 0)
		cout << "此边不存在!" << endl;
	else
	{	g.edges[u][v] = 0;
		g.e--;
	}
}

int GetOutdegree(MatGraph &g, int p)
{	int degree = 0;
	for (int i = 0; i < g.n; i++)
	{	if (g.edges[p][i] == 1)
			degree++;
	}
	printf("结点%d的出度=%d", p, degree);

}

int main()
{	MatGraph g;
	int A[MAXV][MAXV] = {{0, 1, 0, 1, 1}, {1, 0, 1, 1, 0},
		{0, 1, 0, 1, 1}, {1, 1, 1, 0, 1}, {1, 0, 1, 1, 0}
	};
	int n = 5, e = 8;
	CreateMat(g, A, n, e);
	cout << "原邻接矩阵:" << endl;
	DispMat(g);

	GetOutdegree(g, 3);
	cout << endl << endl;
	DelArc(g, 3, 1);
	cout << "删除<3,1>后:" << endl;
	DispMat(g);

	GetOutdegree(g, 3);
	cout << endl;

}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值