|
| 1 | +//https://github.com/codeisneverodd/programmers-coding-test |
| 2 | +//더 좋은 풀이가 존재할 수 있습니다. |
| 3 | +//정답 1 - codeisneverodd |
| 4 | +function solution(n, wires) { |
| 5 | + const hasOneOfWire = (tree, [a, b]) => tree.includes(a) || tree.includes(b); |
| 6 | + |
| 7 | + const convertWiresToTree = wires => [...new Set(wires.flat())]; |
| 8 | + |
| 9 | + const generateTree = (wires, tree) => { |
| 10 | + if (!wires.find(wire => hasOneOfWire(tree, wire))) return tree; |
| 11 | + |
| 12 | + const nextWires = wires.filter(wire => !hasOneOfWire(tree, wire)); |
| 13 | + const nextTree = [...tree, ...convertWiresToTree(wires.filter(wire => hasOneOfWire(tree, wire)))]; |
| 14 | + |
| 15 | + return [...new Set(generateTree(nextWires, nextTree))]; |
| 16 | + }; |
| 17 | + |
| 18 | + let minDiff = Infinity; |
| 19 | + const length = convertWiresToTree(wires).length; |
| 20 | + |
| 21 | + wires.forEach((_, i) => { |
| 22 | + const [initWire, ...remainWires] = wires.filter((_, j) => j !== i); |
| 23 | + const lengthA = generateTree(remainWires, convertWiresToTree([initWire])).length; |
| 24 | + const diff = Math.abs(lengthA - (length - lengthA)); |
| 25 | + minDiff = Math.min(diff, minDiff); |
| 26 | + }); |
| 27 | + |
| 28 | + return minDiff; |
| 29 | +} |
0 commit comments