简体   繁体   English

最短路径加权矩阵

[英]Shortest path weighted matrix

Find the shortest path from any element on the leftmost side of a given nxn matrix to any element on the rightmost side of the matrix. 查找从给定nxn矩阵最左侧的任何元素到矩阵最右侧的任何元素的最短路径。

Movement: Movement can only be one square at a time. 移动:一次只能移动一个方块。 You may move left,right, up-left, up-right, down-left, and down-right. 您可以向左,向右,向左,向右,向左向下和向右移动。

Weight: The cost to move from X element to Y on the matrix is |Y - X| 权重:从X元素到矩阵上的Y的成本为| Y-X |

Runtime: Devised Algorithm must be at most O(n 2 ) 运行时:设计算法必须最大为O(n 2

Example: 例:

例

Tried so Far: 到目前为止已尝试:

到目前为止尝试过

Problem with this solution. 此解决方案有问题。

Runtime is O(n 2 Log n 2 ) which is slower than O(n 2 ). 运行时间为O(n 2 Log n 2 ),比O(n 2 )慢。

You can exploit that when you consider the edges in your graph directed, your graph is acyclic and this has a (partial) topological order. 您可以利用它,当您考虑图形中有向边时,图形是非循环的,并且具有(部分)拓扑顺序。 In this case, you can just compute the distance from the left for each node from-left-to-right, ie column bei column. 在这种情况下,您可以只计算从左到右的每个节点从左到左的距离,即bei column列。

In the first column, this distance is 0 for all nodes, ie d(Upper left)=0, d(middle left)=0, d(lower left)=0. 在第一列中,所有节点的距离均为0,即d(左上)= 0,d(左中)= 0,d(左下)= 0。

In the second (and all following) column(s), you have at most three candidate values to pick the minimum from, eg d(Upper middle)=MIN[d(Upper left)+4,d(middle left)+2]=2. 在第二列(及随后的所有列)中,您最多可以从三个候选值中选取最小值,例如d(中上)= MIN [d(左上)+ 4,d(左中)+2 ] = 2。

That is, computing the values from left to right only takes constant time per node, Theta(n^2) overall. 也就是说,从左到右计算值仅需要每个节点恒定的时间,整体为Theta(n ^ 2)。 More generally, for N nodes and M edges, this takes O(NM) for a single-source-shortest-path computation. 更一般而言,对于N个节点和M个边缘,这需要O(NM)进行单源最短路径计算。

[Edit: I removed the reference to dynamic programming as it confuses more than ist helps. [编辑:我删除了对动态编程的引用,因为它比ist的帮助更令人困惑。 Added an example.] 添加了一个示例。]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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