class Graph {
vertices: Set<string>;
edges: Map<string, Array<{to: string; directed: boolean; weight?: number}>>;
constructor() {
this.vertices = new Set();
this.edges = new Map();
}
addVertex(v: string) {
this.vertices.add(v);
if (!this.edges.has(v)) {
this.edges.set(v, []);
}
}
addEdge(from: string, to: string, directed: boolean, weight?: number) {
this.addVertex(from);
this.addVertex(to);
this.edges.get(from)!.push({ to, directed, weight });
if (!directed) {
this.edges.get(to)!.push({ to: from, directed, weight });
}
}
printGraph() {
for (const v of this.vertices) {
const conns = this.edges.get(v)!.map(e => {
const dir = e.directed ? '->' : '↔';
const w = e.weight !== undefined ? ` (weight ${e.weight})` : '';
return `${dir} ${e.to}${w}`;
});
console.log(`${v}: ${conns.join(', ')}`);
}
}
}
// Driver code
const graph = new Graph();
graph.addEdge('A', 'B', true); // directed A->B
graph.addEdge('B', 'C', false); // undirected B<->C
graph.addEdge('C', 'D', true, 5); // directed C->D with weight 5
graph.printGraph();this.edges.get(from)!.push({ to, directed, weight });
Add edge from 'from' vertex to 'to' vertex with direction and optional weight
if (!directed) {
this.edges.get(to)!.push({ to: from, directed, weight });
}
If edge is undirected, add reverse edge from 'to' to 'from'
for (const v of this.vertices) {
const conns = this.edges.get(v)!.map(e => {
const dir = e.directed ? '->' : '↔';
const w = e.weight !== undefined ? ` (weight ${e.weight})` : '';
return `${dir} ${e.to}${w}`;
});
console.log(`${v}: ${conns.join(', ')}`);
}
Print each vertex and its connected edges with direction and weight
A: -> B
B: ↔ C
C: ↔ B, -> D (weight 5)
D: