图的存贮结构----邻接矩阵表示法

图的存贮结构----邻接矩阵表示法,第1张

图的存贮结构----邻接矩阵表示法
#include
#include
typedef struct graph {
	int NoEdge;
	int Vertices;
	int** A;
}Graph;
void CreateGraph(Graph *g, int n , int noedge) {
	int i, j;
	g->NoEdge = noedge;
	g->Vertices = n;
	g->A = (int**)malloc(n*sizeof(int*));
	for (i = 0; i < n;i++) {
		g->A[i] = (int*)malloc(n*sizeof(int));
		for (j = 0; j < n;j++) {
			g->A[i][j] = noedge;
		}
		g->A[i][i] = 0;
	}
}
void Add(Graph*g, int u,int v, int w) {
	if (u < 0 || v < 0 || u > g->Vertices - 1 || v>g->Vertices - 1 || u == v || g->A[u][v] != g->NoEdge) {
		printf("BadInputn");
	}
	else {
		g->A[u][v] = w;
	}
}
void Delete(Graph *g, int u, int v) {
	if (u < 0 || v < 0 || u > g->Vertices - 1 || v>g->Vertices - 1 || u == v || g->A[u][v] == g->NoEdge) {
		printf("BadInputn");
	}
	else {
		g->A[u][v] = g->NoEdge;
		printf("Delete Successfullyn");
	}
}
void Exist(Graph* g, int u, int v) {
	if (u < 0 || v < 0 || u > g->Vertices - 1 || v>g->Vertices - 1 || u == v || g->A[u][v] == g->NoEdge) {
		printf("No Existancen");
	}
	else {
		printf("Element Exists!n");
	}
}
void PrintMatrix(Graph* g) {
	int i,j;
	for (i = 0; i < g->Vertices;i++) {
		for (j = 0; j < g->Vertices;j++) {
			printf("%-4d",g->A[i][j]);
		}
		printf("n");
	}
	printf("***************n");
}
void main() {
	Graph* g;
	g = (Graph*)malloc(sizeof(Graph));
	CreateGraph(g, 4, -1); //在这里网的noedge统一为-1,不再为无穷值,可以看出这是创建了一个网
	PrintMatrix(g);
	Add(g, 1, 0, 4);
	Add(g, 1, 2, 5);
	Add(g, 2, 3, 3);
	Add(g, 3, 0, 1);
	Add(g, 3, 1, 1);
	Delete(g, 1, 0);
	PrintMatrix(g);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5692571.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存