那位大哥哥来帮帮我,图的深度优先搜索问题!谢谢!
下面是对无向图进行深度优先搜索,怎么打印出的结果不全啊,请师傅帮我看看好吗?
#include <stdio.h>
#include <stdlib.h>
#define N 20
typedef struct arc
{
int index; /* 弧头结点在图数组中的序号 */
struct arc *nextarc;
}*Arc;
typedef struct
{
int info; /* 顶点的信息 */
Arc firstarc; /* 每个顶点的第一条边 */
}Graph;
static void CreateGraph(Graph g[]); /* 创建图 */
static int LocateNode(Graph g[], int v, int n); /* 查找顶点在图数组中的序号 */
static void PrintGraph(Graph g[], int n); /* 打印图 */
static void DepthFirstSearch(Graph g[], int i, int temp[]); /* 深度优先搜索 */
int main(void)
{
Graph g[N];
CreateGraph(g);
return 0;
}
static void CreateGraph(Graph g[])
{
int i, j, k, n, e, v1, v2; /* n, e 分别代表顶点的数量和边的数量 */
Arc p, q;
printf("Enter n and e: ");
scanf("%d %d", &n, &e); /* 读取顶点的数量和边的数量 */
printf("Enter every node information: ");
for (k = 0; k < n; k++)
{
scanf("%d", &g[k].info); /* 读取每个顶点的信息 */
g[k].firstarc = NULL; /* 初始化每个顶点的头指针 */
}
printf("Enter every edge: \n");
for (k = 0; k < e; k++)
{
scanf("%d %d", &v1, &v2); /* 读取组成每条边的两个顶点 */
i = LocateNode(g, v1, n);
j = LocateNode(g, v2, n); /* 查找这两个顶点在图数组中的序号 */
if ((p = (Arc)malloc(sizeof(struct arc))) == NULL)
{
exit(1);
}
p -> index = j; /* 指向弧头结点在数组中的序号 */
p -> nextarc = g[i].firstarc; /* 指向弧尾 */
g[i].firstarc = p;
if ((q = (Arc)malloc(sizeof(struct arc))) == NULL)
{
exit(1);
}
q -> index = i;
q -> nextarc = g[j].firstarc;
g[j].firstarc = q;
}
PrintGraph(g, n); /* 打印图,按深度优先搜索 */
}
static int LocateNode(Graph g[], int v, int n)
{
int i;
for (i = 0; i < n; i++)
{
if (g[i].info == v)
{
return i;
}
}
}
static void PrintGraph(Graph g[], int n)
{
int temp[N], i;
for (i = 0; i < n; i++)
{
temp[i] = 0; /* 初始化辅助数组 */
}
for (i = 0; i < n; i++)
{
if (temp[i] == 0)
{
DepthFirstSearch(g, i, temp); /* i 代表下标 */
}
}
putchar('\n');
}
static void DepthFirstSearch(Graph g[], int i, int temp[])
{
int k;
Arc p;
temp[i] = 1; /* 以访问过设置成 1 */
printf("%d ", g[i].info); /* 打印顶点信息 */
p = g[i].firstarc; /* p 指向当前顶点链表的头结点 */
k = p -> index;
while (p)
{
if (temp[k] == 0)
{
DepthFirstSearch(g, k, temp);
}
p = p -> nextarc;
k = p -> index;
}
}