图C实现 - 深度优先搜索

时间:2012-06-24 05:08:18

标签: c graph structure depth-first-search

我正在尝试使用图的邻接列表表示来实现深度优先搜索算法。这是我的代码:

#include<stdio.h>
#include<stdlib.h>
struct edge
{
int vertexIndex;
struct edge *edgePtr;
}edge;

struct vertex
{
int vertexKey;
int visited;
struct edge *edgePtr;
}vertex;


void insertVertex(struct vertex *g, int vertexKey, int *vertexCount)
{
g[*vertexCount].vertexKey=vertexKey;
g[*vertexCount].edgePtr=NULL;
g[*vertexCount].visited=0;
(*vertexCount)++;
}

void insertEdge(struct vertex *g,int vertex1, int vertex2)
{
struct edge *e,*e1,*e2;
e=g[vertex1].edgePtr;
while(e&& e->edgePtr)
{
    e=e->edgePtr;
}
e1=(struct edge *)malloc(sizeof(*e1));
e1->vertexIndex=vertex2;
e1->edgePtr=NULL;
if(e)
e->edgePtr=e1;
else
g[vertex1].edgePtr=e1;

e=g[vertex2].edgePtr;
while(e&& e->edgePtr)
{
    e=e->edgePtr;
}
e2=(struct edge *)malloc(sizeof(*e2));
e2->vertexIndex=vertex1;
e2->edgePtr=NULL;
if(e)
e->edgePtr=e2;
else
g[vertex2].edgePtr=e2;
}

void printGraph(struct vertex *g, int *vertexCount)
{
int i;
struct edge *e;
for(i=0;i<*vertexCount;i++)
{
    printf("%d(%d)",i,g[i].vertexKey);
    e=g[i].edgePtr;
    while(e)
    {
        printf("->%d",e->vertexIndex);
        e=e->edgePtr;
    }
    printf("\n");
}
}

void dfs(struct vertex *g,int vertex1)
{
g[vertex1].visited=1;
printf("%d ",vertex1);
struct edge *e;
e=g[vertex1].edgePtr;

while(e)
{
    if(!(g[e->vertexIndex].visited))
    dfs(g,e->vertexIndex);

    e=e->edgePtr;
}
}
main()
{
struct vertex *g1[10];
int vc1=0;
insertVertex(g1,5,&vc1);
insertVertex(g1,3,&vc1);
insertVertex(g1,4,&vc1);
insertVertex(g1,2,&vc1);
insertVertex(g1,9,&vc1);
insertEdge(g1,0,1);
insertEdge(g1,0,2);
insertEdge(g1,1,3);
insertEdge(g1,1,4);
dfs(g1, 0);
return 0;
}

问题在于,当我运行此代码时,在打印结束时,dfs&#39;输出,程序意外停止,我不明白为什么。你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

我明白了! 有一个小错误..

在main函数中,g1的声明应为

struct vertex g1[10];

而不是

struct vertex *g1[10];

More explanation here: http://iamsoftwareengineer.blogspot.ie/2012/06/c-graph-implementation-with-adjacency.html

:)