### Weighted graphs

• Weighted graphs

• Weighted graph:

• Weighted graph = a graph whose edges have weights

Example:

• The weight of an edge can represent:

 Cost or distance = the amount of effort needed to travel from one place to another Capacity = the maximim amount of flow that can be transported from one place to another

• Representing weighted graphs using an adjacency list

• Representing a weighted graph using an adjacency list::

• Each node in the adjacency graph will contain:

 A neighbor node ID (this field was already discussed previously) A cost field (this field is new)

• Example:

• Graph:

• Representation:

Explanation:

• Row 0 contains the linked list with the following 3 elements:

 (NodeId = 1, link cost = 3): this represent the link (0,1) in the figure above. (NodeId = 3, link cost = 2): this represent the link (0,3) in the figure above. (NodeId = 8, link cost = 4): this represent the link (0,8) in the figure above.

• And so on....

• Class used to represent (define) edges:

 ``` /* ========================================== Edges is stored as Node of a linked list ========================================== */ public class Edge { int NodeID; // The neighbor node double Weight; // Weight of edge Node next; // Link variable } ```

• Class used to represent (define) a graph:

 ``` /* ============================================================= The graph is an array of Edge (Edge[i] = all edges of node i) ============================================================== */ public class Graph { public Edge[] graph; // Array of Edges } ```

• Representing weighted graphs using an adjacency array

• Representing a weighted graph using an adjacency array:

 If there is no edge between node i and node j, the value of the array element a[i][j] = some very large value Otherwise, a[i][j] is a floating value that is equal to the weight of the edge (i, j)

• Example:

• Graph:

• Representation:

 ``` 0 1 2 3 4 5 6 7 8 +- -+ | * 3 * 2 * * * * 4 | // 0 | 3 * * * * * * 4 * | // 1 | * * * 6 * 1 * 2 * | // 2 | 2 * 6 * 1 * * * * | // 3 M = | * * * 1 * * * * 8 | // 4 | * * 1 * * * 8 * * | // 5 | * * * * * 8 * * * | // 6 | * 4 2 * * * * * * | // 7 | 4 * * * 8 * * * * | // 8 +- -+ * = a very large value (infinite) ```

• Class used to represent a graph using an adjacency matrix:

 ``` public class Graph { /* ======================================= The edges of the graph ======================================= */ double[][] M; // M[i][j] = weight of edge (i,j) ... } ```