class Queue {
constructor() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
// 큐에 원소 삽입
enqueue(item) {
this.items[this.tailIndex] = item;
this.tailIndex++;
}
// 맨 처음 원소 추출
dequeue(){
const item = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return item;
}
// 다음으로 꺼내고자 하는 원소가 무엇인지 알려줌
peek() {
return this.items[this.headIndex];
}
// 큐의 길이 구하기
getLength(){
return this.tailIndex -this.headIndex;
}
}
// 구현된 큐 사용
queue = new Queue();
queue.enqueue(5);
queue.dequeue();
1 ---- 2
| \ |
| \ |
| \ |
3 ---- 5
| /
| /
| /
4
| Node | Connected Nodes |
|---|---|
| 1 | 2, 3 |
| 2 | 1, 5 |
| 3 | 1, 4, 5 |
| 4 | 3, 5 |
| 5 | 2, 3, 4 |
완전탐색을 수행하기 위해 사용할 수 있는 방법 중 하나 다익스트라 최단 경로 알고리즘과 유사한 특징이 있다.1) 다익스트라 알고리즘은 일반 큐 대신에 우선순위 큐를 사용한다.
2) 다익스트라는 특정 노드에 대하여 최단 거리 값이 갱신될 수 있다. (더 짧은 경로를 찾는 경우)
function bfs(graph, start, visited) {
queue = new Queue();
queue.enqueue(start);
// 현재 노드 방문 처리
visited[start] = true;
// 큐가 빌 때까지 반복
while (queue.getLength() != 0) {
// 큐에서 하나의 원소를 뽑아 출력하기
q = queue.dequeue();
// 아직 방문하지 않은 인접한 원소들을 큐에 삽입
for (i of graph[q]) {
if (!visited[i]) {
queue.enqueue(i);
visited[i] = true;
}
}
}
}