https://school.programmers.co.kr/learn/courses/30/lessons/86971
BFS 이용
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;
}
Tree 이용
class Tree {
constructor(n) {
this.tree = new Array(n + 1);
this.min = n;
}
setConnect(v1, v2) {
this.connect(v1, v2);
this.connect(v2, v1);
}
connect(v, target) {
const connects = this.tree[v] || [];
connects.push(target);
this.tree[v] = connects;
}
setDiff(v1, v2) {
const diff = Math.abs(this.getCount(v1, v2) * 2 - (this.tree.length - 1)); // 전력망 차이 Count - (Length - Count);
this.min = Math.min(this.min, diff);
}
getCount(v, except) {
return this.tree[v].reduce((acc, cur) => {
if (cur === except) return acc;
return acc + this.getCount(cur, v);
}, 1);
}
}
function solution(n, wires) {
const tree = new Tree(n);
wires.forEach(([v1, v2]) => tree.setConnect(v1, v2));
wires.forEach(([v1, v2]) => tree.setDiff(v1, v2));
return tree.min;
}
'Coding Test > Programmers' 카테고리의 다른 글
[Programmers] (2021 카카오 채용연계형 인턴십) Lv 2. 거리두기 확인하기 (1) | 2023.03.23 |
---|---|
[Programmers] Lv 2. 가장 큰 정사각형 찾기 (0) | 2023.03.20 |
[Programmers] (Summer/Winter Coding(~2018)) Lv 2. 배달 (0) | 2023.03.16 |
[Programmers] (2021 Dev-Matching: 웹 백엔드 개발자(상반기)) Lv 2. 행렬 테두리 회전하기 (0) | 2023.03.15 |
[Programmers] (2020 카카오 인턴십) Lv 2. 수식 최대화 (0) | 2023.03.13 |
댓글