简体   繁体   中英

Algorithm to add weights in a directed graph (using adjacency matrix)

在此处输入图片说明

I apologize for the terrible graph I made in Paint.

Anyways, I'm having a hard time coming up with a single method on how to add weights in a graph.

Can anyone provide (using pseudocode) some insight on how to go about solving this problem. I've thought about using method overloading but it wouldn't work for every case. I am completely stuck. Keep in mind that I am using an adjacency matrix and not a list. Thank you!

Example:

Distance from Node 1 to Node 2 to Node 3 = 6

Distance from Node 1 to Node 2 to Node 3 to Node 4 = 8

Distance from Node 1 to Node 2 to Node 3 to Node 4 to Node 2 to Node 3 = 18

Let's take the adjacency matrix for this graph you've provided, it looks like this let INF be a nonexistant link.

   1   2   3   4
1 INF  3  INF  3 
2 INF INF  3  INF
3 INF INF INF  2
4 INF  7  INF INF

This stores all the relevant information about the graph, and provides some extremely simple algorithms. To get the weight of a particular edge from node x to y, simply take AdjacencyMatrix[x][y] . Either it'll be a weight, or INF indicating no link exists.

At that point, summing the weight of a path is extremely simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM