😎나의풀이
function solution(n, lighthouse) {
const graph = Array.from({ length: n + 1 }, () => []);
const visited = new Array(n + 1).fill(false);
const res = Array.from({ length: n + 1 }, () => [0, 0]);
for (let [s, e] of lighthouse) {
graph[s].push(e);
graph[e].push(s);
}
const stack = [1];
while (stack.length > 0) {
const node = stack.pop();
if (!visited[node]) {
visited[node] = true;
stack.push(node);
for (const child of graph[node]) {
if (!visited[child]) {
stack.push(child);
}
}
} else {
for (const child of graph[node]) {
if (res[child][0] > 0) {
res[node][0] += Math.min(res[child][0], res[child][1]);
res[node][1] += res[child][0];
}
}
res[node][0]++;
}
}
return Math.min(res[1][0], res[1][1]);
}