class Graph {
adjacencyList: Map<number, number[]>;
constructor() {
this.adjacencyList = new Map();
}
addEdge(u: number, v: number) {
if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
this.adjacencyList.get(u)!.push(v);
}
print() {
for (const [node, neighbors] of this.adjacencyList.entries()) {
console.log(`${node} -> ${neighbors.join(' -> ')}`);
}
}
}
// Tree example
const tree = new Graph();
tree.addEdge(1, 2);
tree.addEdge(1, 3);
// Graph example with cycle
const graph = new Graph();
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1); // cycle edge
console.log('Tree:');
tree.print();
console.log('\nGraph:');
graph.print();this.adjacencyList.get(u)!.push(v);
Add directed edge from node u to node v
Build tree edges without cycles
graph.addEdge(4, 1); // cycle edge
Add edge creating cycle in graph
Print tree adjacency list
Print graph adjacency list showing cycle
Tree:
1 -> 2
1 -> 3
Graph:
1 -> 2
2 -> 3
3 -> 4
4 -> 1