DFS算法实现

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#define infinity 0x3f3f3f
#define N 5
#define E 6
#define target 2
typedef struct edges {
	int node;
	bool visit;
	struct edges* next;
	struct edges* snext;
}edge,*e;
void push(e stack, e node) {
	node->snext = stack->snext;
	stack->snext = node;
}
e pop(e &stack) {
	e node = stack->snext;
	stack = stack->snext;
	return node;
}
typedef struct graph {
	int n;
	e map;
}graph,*g;
int myrand() {
	return rand() % N;
}
void show(g myGraph) {
	for (int i = 0; i < myGraph->n; i++) {
		e temp = &(myGraph->map[i]);
		printf("\n%5d:", temp->node);
		while (temp && temp->next) {
			printf("%5d->", temp->next->node);
			temp = temp->next;
		}
		printf("NULL");
	}
	printf("\n");
}
void DFS(g graphy,int distance[N],bool visit[N]) {
	e node = &graphy->map[target];
	e stack = new edge;
	stack->snext = NULL;
	int length = 0;
	while (stack->snext || !visit[node->node]) {
		if (!visit[node->node]) {
			push(stack, node);
			visit[node->node] = true;
			printf("%5d", node->node);
		}

		//e stemp = stack;
		//while (stemp && stemp->snext) {
		//	printf("*%5d", stemp->snext->node);
		//	stemp = stemp->snext;
		//}
		//printf("\n");
		bool out = false;
		for (int i = 0; i < N&&!out; i++) {
			e temp = &graphy->map[i];
			while (temp && temp->next) {
				if ((graphy->map[i].node == node->node&&!visit[temp->next->node] || !visit[graphy->map[i].node]&&temp->next->node == node->node)) {
					if (temp->next->node == node->node) {
						node = &graphy->map[i];
					}
					else {
						node = temp->next;
					}
					out = true;
					break;
				}
				temp = temp->next;
			}
		}
		if (!out && (stack->snext)) {
			node = pop(stack);
		}
		else if(!out&&!(stack->snext))
			break;
	}
}
int main(void) {
	srand(time(NULL));
	g myGraph = new graph;
	myGraph->n = N;
	myGraph->map = new edge[myGraph->n];
	for (int i = 0; i < myGraph->n; i++) {
		myGraph->map[i].node = i;
		myGraph->map[i].next = NULL;
		myGraph->map[i].visit = false;
		myGraph->map[i].snext = NULL;
	}
	int Edges = E;
	while (Edges) {
		int src = myrand();
		int dst = myrand();
		if (src == dst)
			continue;
		e temp = &(myGraph->map[src]);
		while (temp&&temp->next) {
			temp = temp->next;
		}
		e mye = new edge;
		mye->node = dst;
		temp->next = mye;
		mye->next = NULL;

		temp = &(myGraph->map[dst]);
		while (temp && temp->next) {
			temp = temp->next;
		}
		mye = new edge;
		mye->node = src;
		temp->next = mye;
		mye->next = NULL;
		Edges--;
	}
	show(myGraph);
	/*for (int i = 0; i < myGraph->n; i++) {
		e temp = &(myGraph->map[i]);
		printf("%5d:", temp->node);
		while (temp && temp->next) {
			printf("%5d->", temp->next->node);
			temp = temp->next;
		}
		printf("NULL\n");
	}*/
	int distance[N];
	bool visit[N];
	for (int i = 0; i < N; i++) {
		distance[i] = infinity;
		visit[i] = false;
	}
	DFS(myGraph, distance, visit);
	return 0;
}

你可能感兴趣的:(深度优先,算法,图论)