Edge list is a list of edges with nodes. Essentially, it s a list of all possible connections. it is represented by an array of arrays. Edge list is mostly used when a graph is undirected.
const edges = [
["i", "j"],
["k", "i"],
["m", "k"],
["k", "l"],
["o", "n"],
]; Transformation of Edge list to Adjacency list
Edge list, by itself is not very useful if you want to traverse through a graph. To be able to do that, you have transform the edge list to adjacency list. Below is an example of how to do it.
const edges = [
["i", "j"],
["k", "i"],
["m", "k"],
["k", "l"],
["o", "n"],
];
function buildGraph(edges) {
const graph = {};
edges.forEach((edge) => {
const [a, b] = edge;
if (!graph[a]) graph[a] = [];
if (!graph[b]) graph[b] = [];
graph[a].push(b);
graph[b].push(a);
});
return graph;
}
// Output:
/*
{
i: [ 'j', 'k' ],
j: [ 'i' ],
k: [ 'i', 'm', 'l' ],
m: [ 'k' ],
l: [ 'k' ],
o: [ 'n' ],
n: [ 'o' ]
}
*/