As we know that the graphs can be classified into different variations. They can be directed or undirected, and they can be weighted or unweighted. Here we will see how to represent weighted graph in memory. Consider the following graph −
To store weighted graph using adjacency matrix form, we call the matrix as cost matrix. Here each cell at position M[i, j] is holding the weight from edge i to j. If the edge is not present, then it will be infinity. For same node, it will be 0.
In the adjacency list, each element in the list will have two values. The first one is the destination node, and the second one is the weight between these two nodes. The representation is like below.