Graphs

Graphs can be confused with trees, however there is a difference between the two as graphs do not have a root node but instead have links to other nodes without a structure. There are many way to represent a graph in a visual format with the use of graph diagrams.

Here is an example of a graph diagram, as you can see there is no root node but all nodes are connected by edges.

A way to actually implement a graph is through an adjacency matrix which can be seen here:

Here is a graph diagram and code for an adjacency matrix, the arrows within the diagram represent the edges within the matrix. The 1’s and 0’s within the code show what whether or a not a node has an edge to a another node or not. If a 1 is present then there is an edge, if it is a 0 then there is no edge. A benefit to using an adjacency matrix is that is quite easy to add and remove edges as you just need to access an index within a list, as you can see I have done this within my code. However, it is very inefficient to have an adjacency matrix as it stores ‘non-edges’ which takes up unnecessary memory.

Also to find a nodes neighbour takes more time than other data structures due to the fact that you have to loop through all of the matrix’s rows and columns to find the neighbour of a specific node.

Another data structure that is better at finding the neighbour of a node is an adjacency list as this structure stores the nodes neighbours within a dictionary and you just have to search for the key of the node you want to see the neighbours of and you will get the result straight away instead of looping through all of the rows and columns that you do within an adjacency matrix.

Leave a Reply