问题描述
给定一个无限网格,我们需要找出从给定源到达目的地所需的最低成本。成本计算如下。 只允许对角移动。 仅当方向改变时成本才会增加。类似于国际象棋中的主教移动。您可以根据需要在同一对角线上移动任意数量的单元格,而不会产生任何额外费用。如果源是 (1,1) 而目的地是 (3,3) 成本是 1。
有人可以帮助我使用有效的算法来实现这一点。
解决方法
您可以从任何地方到达任何地方,方向的变化不超过 1 次。因此,如果源和目标在同一对角线上,则成本为零。否则成本为 1。
查找实际路径:
Let source be at xs,ys
Let destination be xd,yd
Specify four diagonal lines passing through the points
y = ys + ( xs - x )
y = ys - ( xs - x )
Is destination on one of these lines? If so,done.
y = yd + ( xd - x )
y = yd - ( xd - x )
Calculate line intersection ( https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection )
There will be two - select one
Travel from source to intersection point
Travel from intersection to destination