Weighted graphs

A weighted graph is a graph that has a numeric weight associated with the edges in the graph. It can be either a directed or an undirected graph. This numerical value can possibly be used to indicate distance or cost, depending upon the purpose of the graph. Let's consider an example. The following graph indicates different ways to get from the A node to the node. You can either go straight from A to D, or choose to pass through B and C, considering that the associated weight with each edge is the amount of time, in minutes, for the journey to the next node:

In this example, AD and ABCD represent two different paths. A path is simply a sequence of edges that you pass through between two nodes. Following these paths, you see that the AD journey takes 40 minutes, whereas the ABCD journey takes 25 minutes. If the only concern is time, then it would be better to travel along the ABCD path, even though it may be a longer route. The point to take away here is that edges can be directed and may hold other information (for example, time taken, distance to be traveled, and so on).

We can implement our graphs in a similar manner to what we have done with other data structures, such as linked lists. With graphs, it makes sense to see edges as objects, just as nodes. Just like nodes, edges can also contain extra information that makes it necessary to follow a particular path. The edges in the graphs can be represented using the links between different nodes; if there is a directed edge in the graph, we can implement it with an arrow pointing from one node to another, which is easy to represent in the node class by using next or previous, parent, or child.

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

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