프로그래머스 Lv. 3 '가장 먼 노드'
Solved-Algorithm/JavaScript/프로그래머스/3/49189. 가장 먼 노드 at main · ParkBible/Solved-Algorithm
This is an auto push repository for Baekjoon Online Judge created with [BaekjoonHub](https://github.com/BaekjoonHub/BaekjoonHub). - ParkBible/Solved-Algorithm
github.com
거리를 묻는 문제인만큼 전형적인 BFS 포맷으로 풀 수 있는 문제이며, 인접 노드 테이블 대신 간선 좌표를 주기 때문에 변환이 필요하다.
function solution(n, edge) {
const graph = {};
// 간선 좌표를 인접 노드 테이블 - {node: [nodes]} 형태로 변환
for (const [a, b] of edge) {
if (!graph[a]) graph[a] = [];
if (!graph[b]) graph[b] = [];
graph[a].push(b);
graph[b].push(a);
}
// ------
const table = {};
const bfs = (graph, start) => {
const visited = new Set([start]);
const queue = [[start, 0]];
while (queue.length > 0) {
const [node, dist] = queue.shift();
// 가장 긴 거리인 노드가 뭔지 찾기 위해 테이블 - {dist: [nodes]} 만들기
if (table[dist]) {
table[dist].push(node);
} else {
table[dist] = [node];
}
// ------
for (const next of graph[node]) {
if (!visited.has(next)) {
queue.push([next, dist + 1]);
visited.add(next);
}
}
}
}
bfs(graph, 1);
// 가장 긴 거리가 뭔지 table에서 찾음
const maxDist = Math.max(...Object.keys(table));
return table[maxDist].length;
}
'IT > JavaScript & TypeScript' 카테고리의 다른 글
| [React/TypeScript] 통합 회원관리 시스템(IAM) 프론트 구현 기록 (0) | 2025.12.20 |
|---|---|
| [JavaScript] DFS 상태 트리 (0) | 2025.11.08 |
| [JavaScript] 함수 (0) | 2025.11.02 |
| [TypeScript] Null, Undefined 체크 (0) | 2025.10.31 |
| [TypeScript] 문자열 key 검증하기 (0) | 2025.10.28 |