export type Node = T; export type Edge = [Node, Node]; export type Graph = Map, Array>>; export function createGraph( nodes: Array>, edges: Array>, ): Graph { const graph: Graph = new Map(); for (const node of nodes) { const neighbours = edges.reduce( (acc, edge) => { if (edge[0] === node) { acc.push(edge[1]); return acc; } if (edge[1] === node) { acc.push(edge[0]); return acc; } return acc; }, [] as Array>, ); if (neighbours.length > 0) { graph.set(node, neighbours); } } return graph; } export function originDFS(origin: Node, graph: Graph): Array> { const visited: Array> = [origin]; if (!graph.has(origin)) { return visited; } innerDFS(origin, graph, visited); return visited; } function innerDFS( node: Node, graph: Graph, visited: Array>, ): void { const neighbours = graph.get(node)!; for (const node of neighbours) { if (visited.includes(node)) { continue; } visited.push(node); innerDFS(node, graph, visited); } } export function getNeighbours( graph: Graph, node: Node, ): Array> { return graph.has(node) ? graph.get(node)! : []; }