|
深度遍历。该程序无法遍历完,为什么?
[code:1]
#include <stdio.h>
#define vnum 20
typedef struct arcnode
{
int adjvex;
struct arcnode *nextarc;
} ArcNodeTp;
typedef struct vexnode
{
int vertex;
ArcNodeTp *firstarc;
} AdjList[vnum];
typedef struct linkgraph
{
AdjList adjs;
int vexnum, arcnum;
} LGraphTp;
LGraphTp* Create_LNvGraph (LGraphTp *ga);
int main (void)
{
LGraphTp *ga;
int input;
ga = (LGraphTp *) malloc (sizeof(LGraphTp));
ga = Create_LNvGraph(ga);
Print_LinkList(ga);
printf("\n%s\n%s", "###深度优先搜索###", "请问要搜索的结点号:");
scanf("%d", &input);
DFS(ga, input);
printf("\n\n");
}
LGraphTp* Create_LNvGraph (LGraphTp *ga)
{
ArcNodeTp *p;
int vex, arc, vexs, arcnum;
int i, j, k;
printf("\n无向图邻接表\n");
printf("请输入顶点个数:");
scanf("%d", &vex);
printf("请输入边数个数:");
scanf("%d", &arc);
ga -> vexnum = vex;
ga -> arcnum = arc;
for (i = 0; i < ga -> vexnum; i++)
{
ga -> adjs[i].vertex = i + 1;
ga -> adjs[i].firstarc = NULL;
}
for (k = 0; k < arc; k++)
{
printf("请输入第%d条边两个顶点的编号:", k + 1);
scanf("%d %d", &i, &j);
p = (ArcNodeTp *) malloc (sizeof(ArcNodeTp));
p -> adjvex = j;
p -> nextarc = ga -> adjs[i - 1].firstarc;
ga -> adjs[i - 1].firstarc = p;
p = (ArcNodeTp *) malloc (sizeof(ArcNodeTp));
p -> adjvex = i;
p -> nextarc = ga -> adjs[j - 1].firstarc;
ga -> adjs[j - 1].firstarc = p;
}
return (ga);
}
int Print_LinkList (LGraphTp *ga)
{
ArcNodeTp *p;
int k;
printf("\n目前输入的邻接表为:\n\n");
for (k = 0; k < ga -> vexnum; k++)
{
printf("V%d:%d |", k + 1, ga -> adjs[k].vertex);
p = ga -> adjs[k].firstarc;
while (p != NULL)
{
printf(" -> %d", p -> adjvex);
p = p -> nextarc;
}
printf("\n");
}
}
int DFS (LGraphTp *ga, int v)
{
ArcNodeTp *p;
int j;
static int visited[vnum];
for (j = 0; j < vnum; j++)
visited[vnum] = 0;
printf(" -> %d ", v);
visited[v] = 1;
p = ga -> adjs[v].firstarc;
while (p != NULL)
{
if (! visited[p -> adjvex])
DFS(ga, p -> adjvex);
p = p -> nextarc;
}
}
[/code:1] |
|