반응형
/*
08/16 DFS
*/
#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); //정점과 연결  
	/* [0] = 정점을 의미 */
	graph[0] -> link = createnode(2); // 정점 1번과 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); //dfs함수 호출  
	printf(" \n"); // 끝  
}

/*  노드 생성을 위한 함수 */
node_point createnode(int data)
{
	node_point ptr; // ptr는 공간  
	ptr = (node_point)malloc(sizeof(struct node)); // 메모리 확보  
	ptr -> vertex = data; // 공간에 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) // 링크를 따라가는 반복문  
	// false(NULL)가 될때까지 w는 w링크로 따라감  
		if(!visited[w->vertex])
	dfs(w->vertex); //방문하지 않았다면 dfs호출하여 vertex로 돌아감  
}

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

--------------------------------
Process exited after 0.01584 seconds with return value 0
계속하려면 아무 키나 누르십시오 . . .
*/
반응형

'2019~2020 > 자료구조' 카테고리의 다른 글

bfs-dfs  (0) 2019.08.26
행렬을 이용한 BFS (c)  (0) 2019.08.20
그래프의 탐색  (0) 2019.08.12
이진 탐색트리  (0) 2019.06.17
별 출력 수  (0) 2019.06.14

+ Recent posts