Complete the code to initialize an adjacency matrix for a graph with n vertices.
const adjacencyMatrix: number[][] = Array.from({ length: n }, () => Array(n).fill([1]));
The adjacency matrix is initialized with 0s to indicate no edges between vertices initially.
Complete the code to add an edge from vertex u to vertex v in the adjacency matrix.
adjacencyMatrix[[1]][v] = 1;
To add an edge from u to v, set the matrix at row u and column v to 1.
Fix the error in the code that checks if there is an edge from u to v.
if (adjacencyMatrix[u][[1]] === 1) { console.log('Edge exists'); }
The second index should be v to check the edge from u to v.
Fill both blanks to create a function that returns true if there is an edge from source to target.
function hasEdge(adjacencyMatrix: number[][], source: number, target: number): boolean {
return adjacencyMatrix[[1]][[2]] === 1;
}The function checks adjacencyMatrix[source][target] to see if the edge exists.
Fill all three blanks to create a function that builds an adjacency matrix from a list of edges.
function buildAdjacencyMatrix(n: number, edges: [number, number][]): number[][] {
const matrix = Array.from({ length: n }, () => Array(n).fill(0));
for (const [[1], [2]] of edges) {
matrix[[3]][[2]] = 1;
}
return matrix;
}The function loops over edges, destructuring each edge into u and v, then sets matrix[u][v] = 1.