class Graph {
adjacencyList: Map<number, number[]>;
adjacencyMatrix: number[][];
size: number;
constructor(size: number) {
this.size = size;
this.adjacencyList = new Map();
this.adjacencyMatrix = Array.from({ length: size }, () => Array(size).fill(0));
for (let i = 0; i < size; i++) {
this.adjacencyList.set(i, []);
}
}
addEdgeList(u: number, v: number) {
this.adjacencyList.get(u)!.push(v); // add v to u's list
this.adjacencyList.get(v)!.push(u); // add u to v's list
}
addEdgeMatrix(u: number, v: number) {
this.adjacencyMatrix[u][v] = 1; // mark edge u->v
this.adjacencyMatrix[v][u] = 1; // mark edge v->u
}
printList() {
for (let i = 0; i < this.size; i++) {
const neighbors = this.adjacencyList.get(i)!.join(' -> ');
console.log(`${i}: ${neighbors} -> null`);
}
}
printMatrix() {
console.log(' ' + [...Array(this.size).keys()].join(' '));
for (let i = 0; i < this.size; i++) {
console.log(i + ' [' + this.adjacencyMatrix[i].join(' ') + ']');
}
}
}
// Driver code
const graph = new Graph(4);
// Add edges 0-1, 0-2, 1-3
graph.addEdgeList(0, 1);
graph.addEdgeList(0, 2);
graph.addEdgeList(1, 3);
graph.addEdgeMatrix(0, 1);
graph.addEdgeMatrix(0, 2);
graph.addEdgeMatrix(1, 3);
console.log('Adjacency List:');
graph.printList();
console.log('\nAdjacency Matrix:');
graph.printMatrix();
// Check edge 0-3
console.log('\nCheck edge 0-3:');
const listHasEdge = graph.adjacencyList.get(0)!.includes(3);
const matrixHasEdge = graph.adjacencyMatrix[0][3] === 1;
console.log(`List: ${listHasEdge}`);
console.log(`Matrix: ${matrixHasEdge}`);
// Add edge 2-3
graph.addEdgeList(2, 3);
graph.addEdgeMatrix(2, 3);
console.log('\nAfter adding edge 2-3:');
console.log('Adjacency List:');
graph.printList();
console.log('\nAdjacency Matrix:');
graph.printMatrix();this.adjacencyList.get(u)!.push(v); // add v to u's list
this.adjacencyList.get(v)!.push(u); // add u to v's list
Add edge in adjacency list for both nodes to keep undirected graph
this.adjacencyMatrix[u][v] = 1; // mark edge u->v
this.adjacencyMatrix[v][u] = 1; // mark edge v->u
Mark edges in adjacency matrix for both directions
const listHasEdge = graph.adjacencyList.get(0)!.includes(3);
const matrixHasEdge = graph.adjacencyMatrix[0][3] === 1;
Check if edge exists using list scan and direct matrix lookup
graph.addEdgeList(2, 3);
graph.addEdgeMatrix(2, 3);
Add new edge 2-3 in both structures
Adjacency List:
0: 1 -> 2 -> null
1: 0 -> 3 -> null
2: 0 -> null
3: 1 -> null
Adjacency Matrix:
0 1 2 3
0 [0 1 1 0]
1 [1 0 0 1]
2 [1 0 0 0]
3 [0 1 0 0]
Check edge 0-3:
List: false
Matrix: false
After adding edge 2-3:
Adjacency List:
0: 1 -> 2 -> null
1: 0 -> 3 -> null
2: 0 -> 3 -> null
3: 1 -> 2 -> null
Adjacency Matrix:
0 1 2 3
0 [0 1 1 0]
1 [1 0 0 1]
2 [1 0 0 1]
3 [0 1 1 0]