# 2. 用栈实现图的深度优先遍历

typedef enum VertexColor
{
Vertex_WHITE = 0,	// 未被搜索到
Vertex_BLACK = 1,	// 子结点都被搜索完毕
Vertex_GRAY = 2	// 子结点正在被搜索
} VertexColor;

typedef struct GNode
{
int number;	// 顶点编号
struct GNode *next;
} GNode;

typedef struct Vertex
{
int number;
int f;
VertexColor color;	// 搜索过程标记搜索状态
struct Vertex *p;
} Vertex;

typedef struct Graph
{
Vertex *vertex;
int VertexNum;
} Graph;

/**
* 深度优先搜索，要求输入图g的结点编号从1开始
*/
void searchByDepthFirst(Graph *g)
{
int VertexNum = g->VertexNum;
Stack *stack = initStack();
Vertex *vs = g->vertex;
int order = 0;

for (int i = 0; i < VertexNum; i++)
{
Vertex *v = vs + i;
v->color = Vertex_WHITE;
v->p = NULL;
push(&stack, v->number);
}

while (!isEmpty(stack))
{
int number = pop(&stack);
Vertex *u = vs + number - 1;
if (u->color == Vertex_WHITE)
{
// 开始搜索该结点的子结点
u->color = Vertex_GRAY;
push(&stack, number);
}
else if (u->color == Vertex_GRAY)
{
// 该结点的子结点已经被搜索完了
u->color = Vertex_BLACK;
u->f = order++;
continue;
}
else
{
continue;
}
{
// 展开子结点并入栈
Vertex *v = vs + links->number - 1;
if (v->color == Vertex_WHITE)
{
v->p = u;
}
}
}
}

typedef struct Stack {
int value;
struct Stack *pre;
} Stack;

Stack* initStack()
{
Stack *s = (Stack *)malloc(sizeof(Stack));
s->pre = NULL;
return s;
}

void push(Stack **s, int value)
{
Stack *n = (Stack *)malloc(sizeof(Stack));
n->pre = *s;
n->value = value;
*s = n;
}

int pop(Stack **s)
{
if ((*s)->pre == NULL)
{
return INT_MAX;
}

int value = (*s)->value;
Stack *pre = (*s)->pre;
free(*s);
*s = pre;
return value;
}

int isEmpty(Stack *s)
{
if (s->pre == NULL)
{
return 1;
}
return 0;
}

void destroyStack(Stack **s)
{
while (*s != NULL)
{
Stack *pre = (*s)->pre;
free(*s);
*s = pre;
}
}

Graph graph;
graph.VertexNum = 5;
Vertex v[5];
Vertex v1; v1.number = 1; v1.p = NULL; v[0] = v1;
Vertex v2; v2.number = 2; v2.p = NULL; v[1] = v2;
Vertex v3; v3.number = 3; v3.p = NULL; v[2] = v3;
Vertex v4; v4.number = 4; v4.p = NULL; v[3] = v4;
Vertex v5; v5.number = 5; v5.p = NULL; v[4] = v5;
graph.vertex = v;

GNode nodes[5];
GNode n1; n1.number = 1;
GNode n2; n2.number = 2;
GNode n3; n3.number = 3;
GNode n4; n4.number = 4;
GNode n5; n5.number = 5;

GNode y; y.number = 5;
GNode e; e.number = 2;
GNode f; f.number = 5;
GNode g; g.number = 2;
GNode h; h.number = 4;

n1.next = &e; e.next = NULL;
n2.next = &h; h.next = &f; f.next = NULL;
n3.next = &g; g.next = NULL;
n4.next = &y; y.next = NULL;
n5.next = NULL;
nodes[0] = n1;
nodes[1] = n2;
nodes[2] = n3;
nodes[3] = n4;
nodes[4] = n5;

searchByDepthFirst(&graph);
printf("\n");
printPath(&graph, 2);

# 3. 图的拓扑排序

/**
* 有向无环图的拓扑排序
*/
void topologySort(Graph *g, int **order, int *n)
{
searchByDepthFirst(g);
*n = g->VertexNum;
*order = (int *)malloc(sizeof(int) * *n);
for (int i = 0; i < *n; i++)
{
(*order)[*n - 1 - g->vertex[i].f] = i + 1;
}
}

# 4. 总结

• 本文已收录于以下专栏：

举报原因： 您举报文章：图的深度优先搜索及拓扑排序 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)