Validating Graphs in javascript

A graph matrix representation is valid if and only if the matrix’s diagonal values are all 0. A can’t have a connection to itself right? It must always be 0, weighted or not.

We can check this by moving only through the diagonal indexes in the matrix. If one looks closely, a pattern emerges. The indexes for the diagonal are the ones where i = j (e.x. [0][0], [1][1], [2][2]). We can iterate with a single loop and increment both indexes by one to validate them.

Identifying a Graph’s Type in Javascript

There are three types of graphs.

Undirected

A graph where all connections are undirected. A can move to B, and B can move to A.

Directed

A graph where all connections are directed. A can move to B, but B can’t move to A.

Mixed

A graph where connections may be directed or undirected.

We count all directed and undirected connections. If all connections are directed, we have a directed graph, if all are undirected, the graph is undirected. If there is a mix of them, the graph is mixed.

To check this we can compare each the graph at [i][j] and [j][i]. This way the algorithm will check all direct connections in pairs. Is A’s path to B equal to B’s path to A? If you look closely, the index at graph[0][1] represent A ‘s connection to B and graph[1][0] represents B’s connection to A.

Experiment with different graphs

Feel free to experiment with these graphs to check the algorithm.

Bringing it all together

Conclusion

The Graph is one of the most, if not the most, powerful data structure there is. Complicated networks can be modeled with them, and there are endless applications.

Today we learned what a graph is, the types of graphs there are, (Directed, Undirected and Mixed). Different ways graphs can be stored in computer memory (Adjacency and Weighted Matrices), and how to implement algorithms to validate and check their type.

This is just an introductory piece. In the following articles, we will dive deeper into understanding the algorithms created by renowned computer scientists to extract powerful information like finding the shortest path between two nodes from a graph.

If you liked this story, don’t forget to follow me for more quality content like this, and if you really liked it — give it a clap or two, don’t be shy.