图的基本概念及其公式

图的基本概念及其公式

创建邻接表

typedef struct ADNode {
	int adjves;   //该边的邻接点编号
	struct ADNode* nexttarc;   //指向下一条边的指针
	int weight;     //该边的相关信息
}ArcNode;   //边结点的类型
typedef struct Vnode {
	char info; //顶点的其他信息
	ArcNode* firstarc;  //指向第一个边节点
}VNode;  //邻接表的头节点类型
typedef VNode AdjList[MAXV];   //邻接表的头节点数组
typedef struct {
	AdjList adjList;
	int n, e;     //邻接表的顶点数n和边数e
}AdjGraph;
void GreatAdj(AdjGraph*& G, int A[][MAXV], int n) {  //创建邻接表
	int i, j; ArcNode* p;
	G->e = 0;
	G = (AdjGraph*)malloc(sizeof(AdjGraph));
	for(int i=0;i<n;i++)
		for(j=n-1;j>=0;j--)
			if (A[i][j] != 0)
			{
				p = (ArcNode*)malloc(sizeof(ArcNode));
				p->adjves = j;
				p->weight = A[i][j];
				p->nexttarc = G->adjList[i].firstarc;
				G->adjList[i].firstarc = p;
				G->e++;

			}

输出邻接表

void DispAdj(AdjGraph* G) {  //输出邻接表
	int i; ArcNode* p;
	for (i = 0; i < G->n; i++) {
		p = G->adjList[i].firstarc;
		printf("%3d", i);
		while (p != NULL) {
			printf("%3d[%d]->", p->adjves, p->weight);
			p = p->nexttarc;
		}
		printf("\n");
	}
}

创建邻接矩阵

typedef struct {  //邻接矩阵算法
	int no;   //顶点编号
	char info;  //顶点其他信息
}VertexType;
typedef struct {
	int edges[MAXV][MAXV];    //邻接矩阵
	int n, e;
	VertexType vexs[MAXV];    //存放顶点信息
}MatGraph;

采用DFS算法深度优先遍历

void DFS(AdjGraph* G, int v) {  //深度优先遍历
	ArcNode* p;
	visited[v] = 1;
	printf("%d", v);
	p = G->adjList[v].firstarc;
	while (p != NULL) {
		if (visited[p->adjves] == 0)
			DFS(G, p->adjves);
		p = p->nexttarc;
	}
}

BFS采用广度优先算法遍历

typedef struct {//创建队列
	int data[MAXV];
	int front , rear;
}SqQueue;
void InitQueue(SqQueue*& q) { //初始化队列
	q = (SqQueue*)malloc(sizeof(SqQueue));
	q->front = q->rear = 0;
}
bool QueueEmpty(SqQueue* q) {  //判断队列是否为空
	return(q->front = q->rear);
}
bool enQueue(SqQueue*& q, int e) {  //进队列
	if (q->rear == MAXV - 1)
		return false;
	q->rear++;
	q->data[q->rear] = e;
	return true;
}
bool deQueue(SqQueue*& q, int& e) {  //出队列
	if (q->front = q->rear)
		return false;
	q->front++;
	e = q->data[q->front];
	return true;
}
void BFS(AdjGraph* G, int v) {  //广度优先算法
	int w, i; ArcNode* p;
	SqQueue* qu;
	InitQueue(qu);
	int visited[MAXV];
	for (i = 0; i < G->n; i++)visited[i] = 0;
	printf("%2d", v);
	visited[v] = 1;
	enQueue(qu, v);
	while (!QueueEmpty(qu)) {
		deQueue(qu, w);
		p = G->adjList[w].firstarc;
		while (p != NULL) {
			if (visited[p->adjves] == 0)
			{
				printf("%2d", p->adjves);
				visited[p->adjves] = 1;
				enQueue(qu, p->adjves);
			}
			p = p->nexttarc;
		}
	}
	printf("\n");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值