Search code examples
javagraphmatrixweighted

How to show a weighted unidirect graph to a two dimensional array (in matrix form)?


enter image description here

Hi guys, trying to do a lab here, but I am unable to understand as to how you can show the nodes in the graph (left), in a three by three matrix (G, right). I'm not looking at how to print a matrix in java.

It says:

Here, the edge between each node i and j is represented by a number that indicates the edge weight. In the diagram, the edge between node 1 and 3 can be seen at row 1, column 3 and has value 2.


Solution

  • Each node is given an index (starting at 0). In this case, Node 1 has index 0, Node 2 has index 1, and Node 3 has index 2. To find the weight between a Node with index i, and a Node with index j, look at G[i][j].

    For example, to find the weight between Node 1 and Node 3, you look at the matrix entry G[0][2], which is 2.

    Because it is an undirected graph, it doesn't matter which node is the start and which is the end, so the top half of the matrix is the same as the bottom half.