본문 바로가기
자료구조

연결리스트 깊이 탐색

by chaechaekim 2019. 8. 16.
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 8 // 노드 최고 개수 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); // DFS함수 선언  
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(3);
	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); // 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) //link를 따라가는 반복문
	// False이면 빠져나감
		if (!visited[w->vertex])
			dfs (w->vertex);
}

/*

 : V0 ->V1 ->V3 ->V7 ->V4 ->V5 ->V2 ->V6 -> 

-------------------------------- 
Process exited after 0.01919 seconds with return value 0 
계속하려면 아무 키나 누르십시오 . . .

*/

/*

 : V0 ->V1 ->V3 ->V7 ->V4 ->V5 ->V2 ->V6 ->

--------------------------------
Process exited after 0.01919 seconds with return value 0
계속하려면 아무 키나 누르십시오 . . .

*/

'자료구조' 카테고리의 다른 글

dfs-bfs(연결리스트)  (0) 2019.08.23
행렬을 이용한 BFS  (0) 2019.08.20
그래프 p.93  (0) 2019.08.12
재귀알고리즘을 사용한 이진 트리 순회  (0) 2019.06.11
변수 값 교환 함수  (0) 2019.05.21

댓글