我一直在尝试创建一个程序,在DFS搜索期间关闭图表中的节点。因此,在图1-> 2-> 3中,它应该打印:3 2 1,不知何故,下面的代码将打印3 1 2,一般情况下 对于像上面那样的简单图形,它将打印n 1 2 ... n-2 n-1。 如果你知道我做错了什么请分享。
#include <stdio.h>
#include <stdlib.h>
#define UNVISITED 0
#define VISITING 1
#define CLOSED 2
typedef struct node{
int id;
struct node *next;
}Node;
typedef struct graph{
int V,E;
int *visited;
Node ** list;
Node* order;
}Graph;
Graph *makeGraph(){
int v,e,i;
scanf("%d %d",&v ,&e);
Graph* g = (Graph*)malloc(sizeof(Graph));
g->V=v;
g->E=e;
g->order =NULL;
g->list = (Node**)malloc(v*sizeof(Node*));
g->visited = (int*)malloc(v*sizeof(int));
for(i=0;i<v;++i){
g->list[i]=NULL;
g->visited[i]=UNVISITED;
}
return g;
}
void createArcs(Graph *g){
int from,to;
Node *n = (Node*)malloc(sizeof(Node));
for(int i=0;i<g->E;++i){
scanf("%d %d",&from ,&to);
n->id = to;
n->next = g->list[from-1];
g->list[from-1]=n;
}
return;
}
void visitNode(Graph *g, int i){
if(g->visited[i]==CLOSED)
return;
else if(g->list[i]==NULL){
printf("%d\t", i+1);
g->visited[i]=CLOSED;
return;
}
Node* n = g->list[i];
while(n!=NULL){
visitNode(g,n->id-1);
n=n->next;
}
printf("%d\t", i+1);
g->visited[i]=CLOSED;
return;
}
int main()
{
Graph *g = makeGraph();
createArcs(g);
for(int i=0;i<g->V;i++)
visitNode(g,i);
return 0;
}