1、输入有向图的顶点和弧的数据,建立该有向图的邻接表,要求在链表插入时候使用头插入法;2、实现该有向图的深度优先遍历,并输出结果;

【问题描述】

1、输入有向图的顶点和弧的数据,建立该有向图的邻接表,要求在链表插入时候使用头插入法;

2、实现该有向图的深度优先遍历,并输出结果;

3、遍历序列从输入的第一个结点开始。

5 6                        //节点数 边数
A B C D E            //节点数据
A B                     //联通边
A C
A D
D E
E C
C B

【输出形式】输出图的深度优先遍历序列和图的广度优先遍历序列,每个字符之间用一个空格隔开。

A  D  E  C  B

【代码实现】

#include <iostream>
#include <algorithm>
#define INIT_MAX 9999
using namespace std;

typedef struct Arcnode {
	int Adjvex;
	struct Arcnode *next;
}Arcnode;

typedef struct Vnode {
	char data;
	Arcnode *first;
}Vnode,Adjlist[100];

typedef struct {
	Adjlist vexs;
	bool visited[100];
	int vexnum, arcnum;
}Graph;

void create_graph(Graph &G) {
	cin >> G.vexnum >> G.arcnum;
	char ch;
	for (int i = 0; i < G.vexnum; i++) {
		cin >> ch;
		G.vexs[i].data = ch;
		G.vexs[i].first = NULL;
		G.visited[i] = 0;
	}
	char v0, v1;
	Arcnode *p;
	for (int j = 0; j < G.arcnum; j++) {
		int t0 = 0, t1 = 0;
		cin >> v0 >> v1;
		while (G.vexs[t0].data != v0)
			t0++;
		while (G.vexs[t1].data != v1)
			t1++;
		p = (Arcnode*)malloc(sizeof(Arcnode));
		p->Adjvex = t1;
		p->next = G.vexs[t0].first;
		G.vexs[t0].first = p;
	}
}

int Firstadjvex(Graph G, int v) {
	if (v<0 || v>INIT_MAX)
		return -1;
	Arcnode *p=G.vexs[v].first;
	if (p != NULL)
		return p->Adjvex;
	else
		return -1;
}

int Nextadjvex(Graph G, int v, int w) {
	if (v<0 || v>INIT_MAX)
		return -1;
	if (w<0 || w>INIT_MAX)
		return -1;
	Arcnode *p = G.vexs[v].first;
	while (p != NULL&&p->Adjvex != w)
		p = p->next;
	if (p->next != NULL)
		return p->next->Adjvex;
	else
		return -1;
}

void DFS(Graph &G, int v) {
	G.visited[v] = 1;
	cout << (char)G.vexs[v].data << " ";
	for (int w = Firstadjvex(G, v); w > 0; w = Nextadjvex(G, v, w)) {
		if (!G.visited[w])
			DFS(G, w);
	}
}
int main() {
	Graph G;
	create_graph(G);
	DFS(G, 0);
	system("pause");
	return 0;
}

【验证结果】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mingyuan Deng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值