Skip to main content

--description--

Another way to represent a graph is to put it in an adjacency matrix. An adjacency matrix is a two-dimensional (2D) array where each nested array has the same number of elements as the outer array. In other words, it is a matrix or grid of numbers, where the numbers represent the edges.

Note: The numbers to the top and left of the matrix are just labels for the nodes. Inside the matrix, ones mean there exists an edge between the vertices (nodes) representing the row and column. Finally, zeros mean there is no edge or relationship.

1 2 3 ------ 1 | 0 1 1 2 | 1 0 0 3 | 1 0 0

Above is a very simple, undirected graph where you have three nodes, where the first node is connected to the second and third node. Below is a JavaScript implementation of the same thing.

var adjMat = [
[0, 1, 1],
[1, 0, 0],
[1, 0, 0]
];

Unlike an adjacency list, each "row" of the matrix has to have the same number of elements as nodes in the graph. Here we have a three by three matrix, which means we have three nodes in our graph. A directed graph would look similar. Below is a graph where the first node has an edge pointing toward the second node, and then the second node has an edge pointing to the third node.

var adjMatDirected = [
[0, 1, 0],
[0, 0, 1],
[0, 0, 0]
];

Graphs can also have weights on their edges. So far, we have unweighted edges where just the presence and lack of edge is binary (0 or 1). You can have different weights depending on your application.

--instructions--

Create an adjacency matrix of an undirected graph with five nodes. This matrix should be in a multi-dimensional array. These five nodes have relationships between the first and fourth node, the first and third node, the third and fifth node, and the fourth and fifth node. All edge weights are one.

--hints--

undirectedAdjList should only contain five nodes.

assert(
adjMatUndirected.length === 5 &&
adjMatUndirected
.map(function (x) {
return x.length === 5;
})
.reduce(function (a, b) {
return a && b;
})
);

There should be an edge between the first and fourth node.

assert(adjMatUndirected[0][3] === 1 && adjMatUndirected[3][0] === 1);

There should be an edge between the first and third node.

assert(adjMatUndirected[0][2] === 1 && adjMatUndirected[2][0] === 1);

There should be an edge between the third and fifth node.

assert(adjMatUndirected[2][4] === 1 && adjMatUndirected[4][2] === 1);

There should be an edge between the fourth and fifth node.

assert(adjMatUndirected[3][4] === 1 && adjMatUndirected[4][3] === 1);

--seed--

--seed-contents--

var adjMatUndirected = [];

--solutions--

var adjMatUndirected = [
[0, 0, 1, 1, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 0, 1, 1, 0]
];