function createAdjacencyList(edges) {
const adj = {};
for (const [begin, end, cost] of edges) {
adj[begin] ??= [];
adj[end] ??= [];
adj[begin].push([end, cost]);
adj[end].push([begin, cost]);
}
return adj;
}
function furthest(adj, start) {
let maxCost = 0;
let result = start;
function dfs(parent, node, totalCost) {
if (totalCost > maxCost) {
result = node;
maxCost = totalCost;
}
for (const [end, cost] of adj[node]) {
if (end != parent) dfs(node, end, totalCost+cost);
}
}
dfs(null, start, 0);
return [result, maxCost];
}
function greatestDiameter(adj) {
const anyNode = Object.keys(adj)[0];
const start = furthest(adj, anyNode)[0];
const [end, cost] = furthest(adj, start);
return [start, end, cost];
}
// Demo
const edges = [
[5, 1, 6], // from, to, cost
[6, 1, 7],
[4, 1, 5],
[6, 3, 9],
[6, 2, 8]
];
const adj = createAdjacencyList(edges);
const [start, end, cost] = greatestDiameter(adj);
console.log({start, end, cost});