问题描述
自己编写源程序,把图的深度优先遍历、广度优先遍历改为输出深度优先生成树、广度优先生成树。
问题分析
深度优先搜索遍历类似于树的前序(先根)遍历。从图G中任选一顶点V为初始出发点,首先访问出发点V,并将其标记为已访问过;然后依次从V出发搜索V的每个邻接点W,若W未曾访问过,则以w作为新的出发点出发,继续进行深度优先遍历,直到图中所有和V有路径相通的顶点都被访问到;若此时图中仍有顶点未被访问,则另选一个未曾访问的顶点作为起点,重复上述过程,直到图中所有顶点都被访问到为止。
广度优先搜索类似于树的按层次遍历。首先访问出发点Vi,接着依次访问Vi的所有未被访问过的邻接点Vi1,Vi2,…,Vit,并均标记为已访问过,然后再按照Vi1,Vi2,…,Vit的次序,访问每一个顶点的所有未曾访问过的顶点并均标记为已访问过,依次类推,直到图中所有和初始出发点Vi有路径相通的顶点都被访问过为止。
代码实现
#include <stdio.h>
#include <malloc.h>
#define MAXV 100
#define INF 32767
typedef char InfoType;
typedef struct ANode
{
int adjvex;
struct ANode* nextarc;
int weight;
}ArcNode;
typedef struct Vnode
{
InfoType info; _
ArcNode* firstarc;
}VNode;
typedef struct
{
VNode adjlist[MAXV];
int n, e;
}AdjGraph;
void CreateAdj(AdjGraph*& G, int A[MAXV][MAXV], int n, int e)
{
int i, j;
ArcNode* p;
G = (AdjGraph*)malloc(sizeof(AdjGraph));
for (i = 0; i < n; i++)
G->adjlist[i].firstarc = NULL;
for (i = 0; i < n; i++)
for (j = n - 1; j >= 0; j--)
if (A[i][j] != 0 && A[i][j] != INF)
{
p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = j;
p->weight = A[i][j];
p->nextarc = G->adjlist[i].firstarc; _
G->adjlist[i].firstarc = p;
}
G->n = n; G->e = 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->adjvex, p->weight);
p = p->nextarc;
}
printf("∧\n");
}
}
void DestroyAdj(AdjGraph*& G)
{
int i;
ArcNode* pre, * p; _
for (i = 0; i < G->n; i++)
{
pre = G->adjlist[i].firstarc;
if (pre != NULL)
{
p = pre->nextarc;
while (p != NULL)
{
free(pre);
pre = p;
p = p->nextarc;
}
free(pre);
}
}
free(G);
}
void DFS(AdjGraph* G, int v)
{
ArcNode* p; int w;
visited[v] = 1;
printf("%d ", v); _
p = G->adjlist[v].firstarc;
while (p != NULL)
{
w = p->adjvex;
if (visited[w] == 0)
DFS(G, w);
p = p->nextarc;
}
}
#endif
#ifndef SQ_QUEUE
#define SQ_QUEUE
#define MaxSize 100
typedef struct
{
ElemType data[MaxSize];
int front, rear; // 队首和队尾指针
} SqQueue; _
void InitQueue(SqQueue*& q)
{
q = (SqQueue*)malloc(sizeof(SqQueue));
q->front = q->rear = 0;
}
void DestroyQueue(SqQueue*& q)
{
free(q);
}
bool QueueEmpty(SqQueue* q)
{
return (q->front == q->rear);
}
bool enQueue(SqQueue*& q, ElemType e)
{
if ((q->rear + 1) % MaxSize == q->front) // 队满上溢出
return false;
q->rear = (q->rear + 1) % MaxSize;
q->data[q->rear] = e;
return true;
}
bool deQueue(SqQueue*& q, ElemType& e) _
{
if (q->front == q->rear) // 队空下溢出
return false;
q->front = (q->front + 1) % MaxSize;
e = q->data[q->front];
return true;
}
#endif // SQ_QUEUE
#include "digraph.h"
int main()
{
int A[6][MAXV] = { {0,5,0,7,0,0},
{0,0,4,0,0,0},
{8,0,0,0,0,9},
{0,0,5,0,0,6},
{3,0,0,0,1,0} };
AdjGraph* G;
CreateAdj(G, A, 6, 10);
DispAdj(G);
DestroyAdj(G);
}
运行结果
如有同校学弟学妹们见到这篇博客,切忌不要随意CV,请自主多动手多思考。