๐Ÿ’ป

[์ž๋ฃŒ๊ตฌ์กฐ] ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰(DFS) ๋ณธ๋ฌธ

์ž๋ฃŒ๊ตฌ์กฐ

[์ž๋ฃŒ๊ตฌ์กฐ] ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰(DFS)

๋˜ํšจ๋‹ˆ 2020. 2. 21. 16:38

๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰(DFS=Depth First Search)

๊ธฐ๋ณธ์ ์œผ๋กœ ์ „์ฒด ๋…ธ๋“œ๋ฅผ ๋งน๋ชฉ์ ์œผ๋กœ ํƒ์ƒ‰ํ•˜๊ณ ์ž ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.  ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰์€ ์Šคํƒ(Stack) ์ž๋ฃŒ๊ตฌ์กฐ์— ๊ธฐ์ดˆํ•ฉ๋‹ˆ๋‹ค. 

1. ํƒ์ƒ‰ ์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ์Šคํƒ์— ์‚ฝ์ž…ํ•˜๊ณ  ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค. 

2. ์Šคํƒ์˜ ์ตœ์ƒ๋‹จ ๋…ธ๋“œ์—๊ฒŒ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ธ์ ‘ ๋…ธ๋“œ๊ฐ€ ํ•˜๋‚˜๋ผ๋„ ์žˆ์œผ๋ฉด ๊ทธ ๋…ธ๋“œ๋ฅผ ์Šคํƒ์— ๋„ฃ๊ณ  ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค. ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ธ์ ‘ ๋…ธ๋“œ๊ฐ€ ์—†์œผ๋ฉด ์Šคํƒ์—์„œ ์ตœ์ƒ๋‹จ ๋…ธ๋“œ๋ฅผ ๊บผ๋ƒ…๋‹ˆ๋‹ค. 

3. 2๋ฒˆ ๊ณผ์ •์„ ๋” ์ด์ƒ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์—†์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค. 

 

์Šคํƒ์— ๋…ธ๋“œ1์„ ๋„ฃ๊ณ , ๋…ธ๋“œ 1๊ณผ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ 2๋ฅผ ๋„ฃ๋Š”๋‹ค. ๊ณ„์†ํ•ด์„œ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์œผ๋ฉด ์ˆœ์„œ๋Œ€๋กœ ๋…ธ๋“œ๋ฅผ ๋„ฃ๋Š”๋‹ค. ๋…ธ๋“œ 7์„ ๋„ฃ๊ณ  ๋”์ด์ƒ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฏ€๋กœ popํ•˜์—ฌ ๊บผ๋‚ธ๋‹ค. ์Šคํƒ์— ๋…ธ๋“œ 1๋งŒ ๋‚จ์•˜์„ ๋•Œ๋กœ ๋Œ์•„์™€์„œ ๋…ธ๋“œ 1๊ณผ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ 3, 4๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๋„ฃ๋Š”๋‹ค. ์ดํ›„ ์ฐจ๋ก€๋Œ€๋กœ popํ•˜์—ฌ ์›์†Œ๋ฅผ ๊บผ๋‚ธ๋‹ค. 

 

 

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1001

typeder struct{
      int index;
      struct Node *next;
} Node;

Node** a;
int n, m, c[MAX_SIZE]; //๋ฐฐ์—ด c๋Š” ์—ฐ๊ฒฐ๊ด€๊ณ„๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐฐ์—ด

void addFront(Node *root, int index, int distance){
      Node *node = (Node*)malloc(sizeof(Node));
      node->index = index;
      node->distance = distance;
      node->next = root->next;
      root->next = node;
}

void dfs(int x){
      if(c[x]) return;  //ํ•ด๋‹น ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ–ˆ์œผ๋ฉด ๋น ์ ธ๋‚˜์˜จ๋‹ค
      c[x] = 1; 		  //๋ฐฉ๋ฌธํ–ˆ๋‹ค.
      printf("%d ", x); //๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ์ถœ๋ ฅ
      Node *cur = a[x]->next;
      while(cur!=NULL){
          int next = cur->index;
          dfs(next);    //์žฌ๊ท€์ ์œผ๋กœ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰
          cur = cur->next;
      }
}
int main(void){
scanf("%d %d", &n, &m);
a = (Node**)malloc(sizeof(Node*) * (MAX_SIZE));
for(int i=1; i<=n; i++){
      a[i]= (Node*)malloc(sizeof(Node));
      a[i]->next = NULL;
      }
      for(int i=0; i<m; i++){
          int x, y;
          scanf("%d %d", &x, &y);
          addFront(a[x], y);
          addFront(a[y], x);
      }
      dfs(1);
      return 0;
}
    
    
๋ฐ˜์‘ํ˜•
Comments