数据结构与算法---图的深度优先遍历<码图>

题目描述

  分别用邻接矩阵和邻接链表两种数据结构实现图的深度优先遍历算法,输出遍历的结点序列,并分析算法的时间复杂度。

提交格式  

提交格式:
邻接矩阵数据结构实现void solveA(int n, int m, int e[][2], int out[])函数。
邻接链表数据结构实现void solveB(int n, int m, int e[][2], int out[])函数。
参数n为结点个数,m为边条数,e为所有边,out为输出序列。1<=n<=3000,1<=m<=100000,0<=e[i][j]<n。
遍历的起始结点为0,邻接矩阵数据结构中按行从左到右遍历邻居结点,邻接链表数据结构中按存储顺序遍历邻居结点,图为无向图。
请不要printf输出任何内容。

输出样例

输入样例:
n=5,m=10,e={{2,4},{3,0},{0,2},{3,1},{4,1},{0,1},{3,4},{2,3},{1,2},{0,4}}
输出样例:
solveA:out={0,1,2,3,4}
solveB:out={0,3,1,4,2}

代码

#include <iostream>
using namespace std;
#define MVNUM 100
int map[1000][1000];
 struct ArcNode {
	int data;
	struct ArcNode* next;
}ArcNode,*ALGrapht[MVNUM];
int* visit;
int ptr;
//邻接矩阵
void DFSA(int n, int v, int* out) {
	if (visit[v] == 1)return;
	visit[v] = 1;
	out[ptr++] =v;
	for (int w = 0; w < n; w++) {
		if ((map[v][w] != 0) && (visit[w] != 1))
			DFSA(n, w, out);
	}
	return;
}
void solveA(int n, int m, int e[][2], int out[]) {
	int i, j;
	visit = (int*)malloc(sizeof(int) * n);
	ptr = 0;
	for (i = 0; i < n; i++) {
		visit[i] = 0;
		for (int j = 0; i < n; i++)
			map[i][j] = 0;
	}
	for (int k = 0; k < m; k++) {
		i = e[k][0];
		j = e[k][1];
		map[i][j] = 1;
		map[j][i] = map[i][j];
	}
	DFSA(n, 0, out);
}
//邻接表
void DFSB(int* out, int i) {
	struct ArcNode* p = new struct ArcNode();
	if (visit[i] == 1)return;
	visit[i] = 1;
	out[ptr++] = i;
	p = ALGrapht[i]->next;
	while (p) {
		if (visit[p->data] != 1)
			DFSB(out, p->data);
		p = p->next;
	}
	return;
}
void solveB(int n, int m, int e[][2], int out[]) {
	int i = 0, j = 0;
	visit = (int*)malloc(sizeof(int) * n);
	ptr = 0;
	for (i = 0; i < n; i++) {
		visit[i] = 0;
		ALGrapht[i] = new struct ArcNode();
		ALGrapht[i]->data = i;
		ALGrapht[i]->next = NULL;
	}
	for (int k = 0; k < m; k++) {
		struct ArcNode* r, * q;
		i = e[k][0];
		j = e[k][1];
		struct ArcNode* p1 = new struct ArcNode();
		struct ArcNode* p2 = new struct ArcNode();
		p1->data = j;
		p1->next = NULL;
		r = ALGrapht[i]->next;
		if (r == NULL) {
			ALGrapht[i]->next= p1;
		}
		else {
			while (r->next != NULL) {
				r = r->next;
			}
			r->next = p1;
		}
		p2->data = i;
		p2->next = NULL;
		q = ALGrapht[j]->next;
		if (q == NULL) {
			ALGrapht[j]->next= p2;
		}
		else {
			while (q->next != NULL) {
				q = q->next;
			}
			q->next = p2;
		}
	}
	DFSB(out, 0);
	return;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值