Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Linux
- nestjs
- 인접리스트
- Spring
- css
- TIL
- 인접행렬
- GraphQL
- LifeCycle
- JWT
- 코딩테스트
- bean
- html
- javascript
- 알고리즘
- Interceptor
- OOP
- 자료구조
- Deep Dive
- 프로그래머스
- Kubernetes
- MySQL
- 탐욕법
- dfs
- node.js
- java
- REST API
- typescript
- winston
- puppeteer
Archives
- Today
- Total
처음부터 차근차근
[알고리즘] BFS 본문
728x90
너비 우선 탐색(BFS)이란??
루트 노드(혹은 다른 임의의 노드)에서 시작해서 인접한 노드를 먼저 탐색하는 방법을 의미한다.
- 시작 정점으로부터 가까운 정점을 먼저 방문하고 멀리 떨어져 있는 정점을 나중에 방문하는 순회 방법이다.,
- 사용하는 경우 : 두 노드 사이의 최단 경로 혹은 임의의 경로를 찾고 싶을 때 이 방법을 선택한다.
DFS의 경우 BFS보다 좀 더 복잡하다.
BFS의 특징
- 시작 노드에서 시작해서 거리에 따라 단계별로 탐색하기 때문에 직관적이지 않은 면이 있다.
- 재귀적으로 동작하지 않는다.
- 어떤 노드를 방문했었는지 여부를 반드시 검사해야 한다. 그렇지 않으면 무한 루프에 빠질 위험이 있다.
- BFS는 방문한 노드를 차례로 저장한 후 꺼낼 수 있는 자료 구조인 큐(Queue)를 사용한다.
- 즉, 선입선출 원칙으로 탐색하며, 일반적으로 큐를 이용해서 반복적 형태로 구현하는 것이 가장 잘 동작한다.
BFS 구현 방법
- 시작하고자 하는 노드를 Queue에 넣는다.
- 현재 큐의 노드를 빼고, 방문한 기록을 남긴다.
- 현재 방문한 노드와 인접한 노드 중 방문하지 않는 노드를 큐에 추가한다.
- 2-3을 반복한다.
- Queue가 비면 탐색을 종료한다.
import { Queue } from "./queue";
function BFS(graph: number[][], start: number, visited: boolean[]) {
const queue = new Queue();
queue.enQueue(start);
visited[start] = true;
while (queue.size()) {
const v = queue.deQueue();
console.log(v);
for (const node of graph[v]) {
if (!visited[node]) {
queue.enQueue(node);
visited[node] = true;
}
}
}
}
const graph = [[1, 2, 4], [0, 5], [0, 5], [4], [0, 3], [1, 2]];
const visited = Array(6).fill(false);
BFS(graph, 0, visited);
export class Queue {
private store;
private front: number;
private rear: number;
constructor() {
this.store = {};
this.front = 0;
this.rear = 0;
}
size() {
if (this.store[this.rear] === undefined) {
return null;
} else {
return this.rear - this.front + 1;
}
}
enQueue(value) {
if (this.size() === null) {
this.store["0"] = value;
} else {
this.rear += 1;
this.store[this.rear] = value;
}
}
deQueue() {
let temp;
if (this.front === this.rear) {
temp = this.store[this.front];
delete this.store[this.front];
this.front = 0;
this.rear = 0;
return temp;
} else {
temp = this.store[this.front];
delete this.store[this.front];
this.front++;
return temp;
}
}
}
BFS의 시간 복잡도
- 인접 리스트로 표현된 그래프: O(N+E)
- 인접 행렬로 표현된 그래프: O(N^2)
참조
'CS > 알고리즘' 카테고리의 다른 글
[알고리즘] MergeSort (0) | 2024.01.02 |
---|---|
[알고리즘] Quick 정렬 (1) | 2024.01.02 |
[알고리즘] 버블 정렬, 선택 정렬, 삽입 정렬 (0) | 2023.12.27 |
[알고리즘] Backtracking, N-Queen 문제 (0) | 2023.11.16 |
[알고리즘] DFS (0) | 2023.11.16 |