Use of multi-dimensional arrays to represent data structures

In coming chapters, we will talk about many different data structures and algorithms. One of the key data structures we are going to focus is the graph. We already know the definition of graph data structures. Most of the time we will be using PHP multidimensional arrays to represent that data as an adjacency matrix. Let us consider the following graph diagram:

Now if we consider each node of the graph to be a value of an array, we can represent the nodes as:

$nodes = ['A', 'B', 'C', 'D', 'E'];

But this will only give us node names. We cannot connect or create a relationship between nodes. In order to do that, we need to construct a two-dimensional array where the node names will be keys, and values will be 0 or 1 based on the interconnectivity of two nodes. Since there is no direction provided in the graph, we do not know if A connects to C or if Connects to A. So we will assume both are connected to each other.

First, we need to create an array for the graph and initialize each node of the two-dimensional arrays as 0. The following code will exactly do that:

$graph = [];
$nodes = ['A', 'B', 'C', 'D', 'E'];
foreach ($nodes as $xNode) {
foreach ($nodes as $yNode) {
$graph[$xNode][$yNode] = 0;
}
}

Let us print the array using the following code so that we see how it looks actually before defining the connectivity between nodes:

foreach ($nodes as $xNode) {
foreach ($nodes as $yNode) {
echo $graph[$xNode][$yNode] . " ";
}
echo " ";
}

As no connection between the nodes has been defined, all cells are showing 0. So the output looks like this:

0       0       0       0       0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

Now we will define the connectivity of the nodes in such a way that a connection between the two nodes will be expressed as a value of 1, just like the following code:

$graph["A"]["B"] = 1;
$graph["B"]["A"] = 1;
$graph["A"]["C"] = 1;
$graph["C"]["A"] = 1;
$graph["A"]["E"] = 1;
$graph["E"]["A"] = 1;
$graph["B"]["E"] = 1;
$graph["E"]["B"] = 1;
$graph["B"]["D"] = 1;
$graph["D"]["B"] = 1;

As there is no direction given in the graph diagram, we will consider it as the undirected graph and hence we are setting two values to 1 for each connection. For the connection between A and B, we are setting both $graph["A"]["B"] and $graph["B"]["A"] to 1. We will learn more about defining connectivity between nodes and why we are doing it in later chapters. For now we are just focusing on how to use multidimensional arrays for data structures. We can reprint the matrix and this time, the output looks like this:

0       1       1       0       1
1 0 0 1 1
1 0 0 0 0
0 1 0 0 0
1 1 0 0 0

It will be much more fun and interesting to find out more about graphs and their operations in Chapter 9, Putting Graphs into Action.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset