Shortest Path
Last updated
Last updated
Here is the map of Ex10si0n island. He designed the arrangement of each town (namely A B C D E F G -town) with roads. When the tourist go through a certain path, he or she will pay for a number of coins. The cost of each road is the number inside each diamonds.
You are paying a visit to Ex10si0n island. Can you find the minimum cost for travelling between arbitary two towns?
You may notice that A town is marked in red. The red color have no meanings in current problem.
Graph data
The explanation of Floyed Warshall Algorithm is a little bit complicated in Wiki. From my perspective and understanding, this algorithm is quite easy to understand, the core code is relaxation (松弛操作) while it is the core code of all kinds of Algorithms applied to Shortest Path problems. For the relaxation, the pseudo code below shows how to implement it.
NB: dis[a][b]
means the minimum distance between node A and node B, the dis[][]
array is initialize by infinity number.
That is, for each three distinct node, there are three paths need to be compaired, namely O
, D
, and B
. For each pair of path (or abstract path) to iterate, actually we just need to consider the following question.
We go to B from A. Is the path
A --> B
shorter or we finding a bridge node C and the pathA --> C --> B
shorter?To make it abstract, for any node F, T: if there is a bridge node V can make the distance shorter, adopt it.
As for
dis[F][T]
records the minimum distance rather than a specific path, that means, we can go to T from F with minimum distance to walk regardless of which path.As a result,
dis[from][bridge] + dis[bridge][to]
may not represent the relation of three node likeE -> (F) -> D
. But it can representE -> (F -> G) -> D
due to the specific path is omited, we care about the distance instead.
Full code implementation