π»
[μλ£κ΅¬μ‘°] λλΉ μ°μ νμ(BFS) λ³Έλ¬Έ
λλΉμ°μ νμ(BFS= Breadth First Search) λ λλΉλ₯Ό μ°μ μΌλ‘ νμνλ μκ³ λ¦¬μ¦μ λλ€. κΈ°λ³Έμ μΌλ‘ ν(Queue)λ₯Ό μ΄μ©νμ¬ κ΅¬νν©λλ€.
1. νμ μμ λ Έλλ₯Ό νμ μ½μ νκ³ λ°©λ¬Έ μ²λ¦¬λ₯Ό ν©λλ€
2. νμμ λ Έλλ₯Ό κΊΌλ΄ ν΄λΉ λ Έλμ μΈμ λ Έλ μ€μμ λ°©λ¬Ένμ§ μμ λ Έλλ€μ λͺ¨λ νμ μ½μ νκ³ , λ°©λ¬Έ μ²λ¦¬λ₯Ό ν©λλ€ .
3. 2λ²μ κ³Όμ μ λ μ΄μ μνν μ μμ λκΉμ§ λ°λ³΅ν©λλ€.
λλΉ μ°μ νμμ ν(Queue)μλ£κ΅¬μ‘°μ κΈ°μ΄νλ€λ μ μμ ꡬνμ΄ κ°λ¨ν©λλ€. μ€μ λ‘ κ΅¬νν¨μ μμ΄ ν STLμ μ¬μ©νλ©΄ μ’μΌλ©° νμμ μνν¨μ μμ΄μ O(N)μκ°μ΄ μμλ©λλ€. μΌλ°μ μΈ κ²½μ° μ€μ μν μκ°μ DFSλ³΄λ€ μ’μ νΈμ λλ€.
#include <stdio.h>
#include <stdlib.h>
#define INF 999999999
#define MAX_SIZE 1001
typedef struct{
int index;
struct Node *next;
} Node;
typedef struct{
Node *front;
Node *rear;
int count;
} Queue;
Node++ a;
int n, m, c[MAX_SIZE]; //λ°°μ΄ cλ λ°©λ¬Έν μ 보
void addFront(Node *root, int index){
Node *node = (Node*)malloc(sizeof(Node));
node->index = index;
node->next = root->next;
root->next = node;
}
void queuePush(Queue *queue, int index){
Node *node = (Node*)malloc(sizeof(Node));
node->index = index;
node->next = NULL;
if(queue->count == 0){ //νμ¬ νκ° λΉμ΄μμΌλ©΄
queue->front = node; //μμ μ½μ
}else{
queue->rear->next = node; //λ€μ μ½μ
}
queue->rear = node;
queue->count++;
}
int queuePop(Queue *queue){
if(queue->count == 0){ //κΊΌλΌ λ
Έλκ° μμ λ
printf("ν μΈλνλ‘μ° λ°μ\n");
return -INF;
}
Node *node = queue->front;
int index = node->index;
queue->front = node->next;
free(node);
queue->count--;
return index;
}
void bfs(int start){
Queue q;
q.front = q.rear = NULL;
q.count = 0;
queuePush(&q, start);
c[start] = 1;
while(q.count!=0){ //νκ° λΉ λκΉμ§ λ°λ³΅
int x = queuePop(&q);
printf("%d ",x);
Node *cur = a[x]->next;
while(cur!=NULL){
int next = cur->index;
if(!c[next]){ //ν΄λΉ μΈμ λ
Έλκ° λ°©λ¬Ένμ§ μμ μνλΌλ©΄
queuePush(&q, next);
c[next] = 1; //λ°©λ¬Έ
}
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);
}
bfs(1);
return 0;
}
'μλ£κ΅¬μ‘°' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[μλ£κ΅¬μ‘°] νΈλ¦¬(Tree) (0) | 2020.11.13 |
---|---|
[μλ£κ΅¬μ‘°] κΉμ΄ μ°μ νμ(DFS) (0) | 2020.02.21 |
[μλ£κ΅¬μ‘°] κ·Έλνμ κ°λ κ³Ό ꡬν (0) | 2020.02.21 |
[μλ£κ΅¬μ‘°] μ°μ μμ ν (0) | 2020.02.18 |