Skip to content

Instantly share code, notes, and snippets.

@alexsoyes
Created June 20, 2023 09:58
Show Gist options
  • Save alexsoyes/b33e0c583d4555924c79976de944586d to your computer and use it in GitHub Desktop.
Save alexsoyes/b33e0c583d4555924c79976de944586d to your computer and use it in GitHub Desktop.
Exemple TypeScript : Graphes
class Graph {
adjacencyList: Map<number, number[]>;
constructor() {
this.adjacencyList = new Map<number, number[]>();
}
addVertex(vertex: number) {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}
addEdge(vertex1: number, vertex2: number) {
this.adjacencyList.get(vertex1)?.push(vertex2);
this.adjacencyList.get(vertex2)?.push(vertex1);
}
printGraph() {
for (const [vertex, edges] of this.adjacencyList) {
console.log(`${vertex} => [${edges.join(", ")}]`);
}
}
}
// Create a new graph instance
const graph = new Graph();
// Add vertices
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
graph.addVertex(4);
// Add edges
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
// Print the adjacency list representation of the graph
graph.printGraph();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment