스택 활용 DFS

Simcurity·2024년 6월 16일
0

자료 구조

목록 보기
5/5
#include <stdio.h>
#include <stdlib.h>

#define MAX_VERTICES 50
#define TRUE 1
#define FALSE 0

typedef struct GraphNode{
    int vertex;
    struct GraphNode *link;
} GraphNode;

typedef struct GraphType{
    int n;
    GraphNode *adj_list[MAX_VERTICES];
} GraphType;

typedef struct Stack{
    int items[MAX_VERTICES];
    int top;
} Stack;

int visited[MAX_VERTICES];

void init_Graph(GraphType *g){
    g->n = 0;
    for(int i=0; i<MAX_VERTICES; i++){
        g->adj_list[i] = NULL;
    }
}

void init_Stack(Stack *s){
    s->top = -1;
    for(int i=0; i<MAX_VERTICES; i++){
        s->items[i] = 0;
    }
}

int is_Empty(Stack *s){
    return s->top == -1;
}

void push(Stack *s, int value){
    s->items[++s->top] = value;
}

int pop(Stack *s){
    if(is_Empty(s)){
        fprintf(stderr, "stack underflow");
        return 0;
    }
    return s->items[s->top--];
}

void insert_vertex(GraphType *g, int vertex){
    if(((g->n)+1) > MAX_VERTICES){
        fprintf(stderr, "vertex overflow");
        return;
    }
    g->n++;
}

void insert_edge(GraphType *g, int u, int v){
    GraphNode *node;
    if(u>=MAX_VERTICES || v>=MAX_VERTICES){
        fprintf(stderr, "edge error");
        return;
    }
    node = (GraphNode*)malloc(sizeof(GraphNode));
    node->vertex = v;
    node->link = g->adj_list[u];
    g->adj_list[u] = node;
}

void dfs(GraphType *g, int start){
    Stack *s;
    s = (Stack*)malloc(sizeof(Stack));
    init_Stack(s);
    push(s, start);
    while(!is_Empty(s)){
        start = pop(s);
        if(!visited[start]){
            visited[start] = TRUE;
            printf("%d -> ", start);

            GraphNode *node = g->adj_list[start];
            while(node){
                int adjvertex = node->vertex;
                if(!visited[adjvertex]){
                    push(s, adjvertex);
                }
                node = node->link;
            }
        }
    }
}

int main(){
    GraphType *g;
    g = (GraphType*)malloc(sizeof(GraphType));
    init_Graph(g);
    int vertex, edge, start;
    scanf("%d %d %d", &vertex, &edge, &start);
    for(int i=0; i<vertex; i++){
        insert_vertex(g, i);
    }
    int e1, e2;
    for(int i=0; i<edge; i++){
        scanf("%d %d", &e1, &e2);
        insert_edge(g, e1, e2);
        insert_edge(g, e2, e1);
    }
    dfs(g, start);
    free(g);
    return 0;
}



결과

0개의 댓글