| | | | | |

C언어 자료구조 DFS

Category : Computer Tip's/Programming
Date : 2021. 12. 3. 14:16
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 8
#define FALSE 0
#define TRUE 1
typedef struct node *node_point;
typedef struct node
{
	int vertex;
	node_point link;
};
node_point graph[MAX_VERTICES];
short int visited[MAX_VERTICES];
node_point createnode (int data);
void dfs (int vertex);
int main()
{
	graph[0] = createnode(1);
	graph[0]->link = createnode(2);
	graph[1] = createnode(0);
	graph[1]->link = createnode(3);
	graph[1]->link->link = createnode(4);
	graph[2] = createnode(0);
	graph[2]->link = createnode(5);
	graph[2]->link->link = createnode(6);
	graph[3] = createnode(1);
	graph[3]->link = createnode(7);
	graph[4] = createnode(1);
	graph[4]->link = createnode(7);
	graph[5] = createnode(2);
	graph[5]->link = createnode(7);
	graph[6] = createnode(2);
	graph[6]->link = createnode(7);
	graph[7] = createnode(3);
	graph[7]->link = createnode(4);
	graph[7]->link->link = createnode(5);
	graph[7]->link->link->link = createnode(6);
	printf(" : "); //정점의 운행 순서
	dfs (0);
	printf(" \n"); //끝
}
/*  노드 생성을 위한 함수*/
node_point createnode(int data)
{
	node_point ptr;
	ptr = (node_point)malloc(sizeof(struct node));
	ptr->vertex = data;
	ptr->link = NULL;
	return ptr;
}
void dfs (int v)
{
	/* V 그래프의 정점 에서 시작하는 깊이 우선 탐색 */
	node_point w;
	visited[v] = TRUE;
	printf ("V%d -> ", v);
	for (w=graph[v]; w; w = w-> link)
	if (!visited[w->vertex])
	dfs (w->vertex);
}