Bootstrap

图的表示(邻接矩阵和邻接表)

图的表示有邻接矩阵、关联矩阵、邻接表等方式。

下面用代码实现邻接矩阵和邻接表。

#include<stdio.h>
#include<stdlib.h>
#define MAX 50//maximum number of vertices
typedef char VertexType;

typedef enum{DG,UDG}GraphType;//0 for directed and 1 undirected

typedef struct MyGraph{
	GraphType type;
	VertexType v[MAX];//vertices
	int e[MAX][MAX];//edges
	int nv;//number of vertices
	int ne;//number of edges
}Graph;

int get_index_of_vertex(char v,Graph* p){
	int i;
	for(i=0;i<p->nv;i++){
		if(p->v[i]==v)
			return i;
	}
	return 0;
}

void print(Graph* p){
	int i,j;
	if(p->type==0)
		printf("this is a directed graph\n");
	else
		printf("this is an undirected graph\n");
	printf("vertex set:\n");
	for(i=0;i<p->nv;i++)
		printf("%c ",p->v[i]);
	printf("\n");
	printf("adjacent matrix:\n");
	for(i=0;i<p->nv;i++){
		for(j=0;j<p->nv;j+
;