【问题描述】
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;
}
【验证结果】