https://school.programmers.co.kr/learn/courses/30/lessons/86971
const bfs = (graph, pivot, visited, vistedDuplication) => {
const queue = [pivot];
let cnt = 0;
while (queue.length) {
const dest = queue.shift();
if (vistedDuplication[dest]) return Infinity;
(visited[dest] = true), ++cnt;
for (const to of graph[dest]) {
if (visited[to]) continue;
queue.push(to);
}
}
return cnt;
};
function solution(n, wires) {
const graph = wires.reduce((acc, [a, b]) => {
acc[a].push(b), acc[b].push(a);
return acc;
}, Array.from(Array(n + 1), () => []));
const visitedNone = visitedDivision = new Array(n + 1).fill(false);
let result = Infinity;
graph.forEach((form, idx) => {
for (const division of form) {
visitedNone[idx] = visitedDivision[idx] = true;
const divisionCnt = bfs(graph, division, visitedDivision, visitedNone);
let nodeCnt = 1;
for (const node of form.filter((e) => e !== division))
nodeCnt += bfs(graph, node, visitedNone, visitedDivision);
result = Math.min(result, Math.abs(divisionCnt - nodeCnt));
visitedDivision.fill(false);
visitedNone.fill(false);
}
});
return result;
}
GitHub :
'Coding Test > Programmers' 카테고리의 다른 글
[Programmers] Lv 2. 호텔 대실 (1) | 2023.10.11 |
---|---|
[Programmers] (2020 카카오 인턴십) Lv 2. 수식 최대화 (0) | 2023.10.10 |
[Programmers] (2020 KAKAO BLIND RECRUITMENT) Lv 2. 괄호 변환 (0) | 2023.08.07 |
[Programmers] (2018 KAKAO BLIND RECRUITMENT) Lv 2. [3차] 방금그곡 (0) | 2023.08.07 |
[Programmers] Lv 2. 무인도 여행 (1) | 2023.08.05 |
댓글