
DFS와 BFS는 알고리즘의 기초이자 핵심이라고 할 수 있다.
const graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'G', 'H'],
'D': ['B', 'E', 'F'],
'E': ['D'],
'F': ['D'],
'G': ['C'],
'H': ['C', 'I'],
'I': ['H']
};
function dfs(graph, startNode, visited = new Set(), result = []) {
if (visited.has(startNode)) {
return;
}
visited.add(startNode);
result.push(startNode);
(graph[startNode] || []).forEach(neighbor => {
if (!visited.has(neighbor)) {
dfs(graph, neighbor, visited, result);
}
});
return result;
}
# 그래프 (인접 리스트) 예시
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'G', 'H'],
'D': ['B', 'E', 'F'],
'E': ['D'],
'F': ['D'],
'G': ['C'],
'H': ['C', 'I'],
'I': ['H']
}
# 방문한 노드를 저장할 집합(Set)
visited = set()
def dfs(graph, node):
if node not in visited:
visited.add(node)
for neighbor in graph.get(node, []):
dfs(graph, neighbor)
function bfs(graph, startNode) {
const queue = [startNode];
const visited = new Set([startNode]);
const result = [];
while (queue.length > 0) {
const node = queue.shift();
result.push(node);
(graph[node] || []).forEach(neighbor => {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
});
}
return result;
}
from collections import deque
def bfs(graph, start_node):
queue = deque([start_node])
visited = {start_node}
result = []
while queue:
node = queue.popleft()
result.append(node)
print(f"방문 노드: {node}")
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
# 방문하지 않은 노드는 큐의 맨 뒤에 추가합니다 (append).
queue.append(neighbor)
return result