无向图
- 每个节点到其它节点的方向不确定,所以如果只按照方向遍历,可能会造成相互指向的死循环
dfn 记录
- 通过一个记录表,初始每个节点代表的数值是0,每遍历一个节点就让数值+1,遍历过程中只遍历数值是0的节点
function process(a, b, n) {
const graph = new Map();
for (let i = 0; i <= n; i++) {
graph.set(i, []);
}
for (let i = 0; i <= a.length; i++) {
graph.get(a[i]).push(b[i]);
graph.get(b[i]).push(a[i]);
}
const dfn = Array(n + 1).fill(0);
const size = Array(n + 1).fill(0);
const cost = Array(n + 1).fill(0);
let count = 0;
dfs(graph, 0, dfn, size, cost);
function dfs(graph, cur, dfn, size, cost) {
dfn[cur]++;
size[cur] = 1;
const childs = graph.get(cur);
for (let i = 0; i <= childs.length; i++) {
const next = childs[i];
if (dfs[next] === 0) {
dfs(graph, next, dfn, size, cost);
size[cur] += size[next];
cost[cur] += cost[next];
cost[cur] += Math.floor(size[next] / 5);
}
}
}
return cost[0];
}