DFS
소스 코드
function dfs(graph, v, visited) {
visited[v] = true;
console.log(v);
graph[v].forEach(i => {
if (!visited[i]) {
dfs(graph, i, visited);
}
})
}
const graph = [
[],
[2, 3, 8],
[1, 7],
[1, 4, 5],
[3, 5],
[3, 4],
[7],
[2, 6, 8],
[1, 7]
];
const visited = new Array(graph.length).fill(false);
dfs(graph, 1, visited);
BFS
소스 코드
function bfs(graph, v, visited) {
const queue = [v];
visited[v] = true;
while (queue.length !== 0) {
const node = queue.shift();
console.log(node);
graph[node].forEach(i => {
if (!visited[i]) {
queue.push(i);
visited[i] = true;
}
})
}
}
const graph = [
[],
[2, 3, 8],
[1, 7],
[1, 4, 5],
[3, 5],
[3, 4],
[7],
[2, 6, 8],
[1, 7]
];
const visited = new Array(graph.length).fill(false);
bfs(graph, 1, visited);