DFS/ BFS
🔑대표적 그래프(Graph) 탐색 알고리즘인 DFS/BFS를 소개합니다.
그래프(Graph)는 뭘까?
그래프 탐색
DFS(Depth-First Search, 깊이 우선 탐색)
class Graph { constructor() { this.adjacencyList = {}; } // 정점(노드) 추가 addVertex(vertex) { if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = []; return this.adjacencyList; } // 간선 추가 addEdge(vertex1, vertex2) { this.adjacencyList[vertex1].push(vertex2); this.adjacencyList[vertex2].push(vertex1); return this.adjacencyList; } // 탐색 시작 노드 인자 DFS(start) { const result = []; // 탐색 결과 배열 const visited = {}; // 방문한 노드 체크(각 노드를 한 번씩만 처리하도록) const adjacencyList = this.adjacencyList; function dfs(vertex) { // 정점이 빈 값이면 null을 반환 if (!vertex) return null; // 시작 노드를 스택에 push하고 방문 처리 visited[vertex] = true; // 탐색 결과 배열에 노드 push result.push(vertex); // 인접 리스트를 순회하면서 현재 노드와 연결된 다른 노드 방문 처리 adjacencyList[vertex].forEach((v) => { // 방문하지 않은 인접 노드 방문 처리(재귀) if (!visited[v]) dfs(v); }); } dfs(start); return result; } } const graph = new Graph(); graph.addVertex("A"); graph.addVertex("B"); graph.addVertex("C"); graph.addVertex("D"); graph.addVertex("E"); graph.addVertex("F"); graph.addEdge("A", "B"); graph.addEdge("A", "C"); graph.addEdge("B", "D"); graph.addEdge("C", "E"); graph.addEdge("D", "E"); graph.addEdge("D", "F"); graph.addEdge("E", "F"); graph.DFS("A") // ["A", "B", "D", "E", "C", "F"]
BFS(-First Search, 너비 우선 탐색)
💡정리
Reference
Last updated





