Finding the most natural route between two points on a grid

时间:2016-07-11 20:29:07

标签: c algorithm performance artificial-intelligence

How can I find the most natural route (something a human might take) between two points assuming that I have an array of bytes, with each bit representing a fixed size square and indicating whether it is accessible or not? For example, assuming the array represents the following grid:enter image description here

Where grey squares cannot be crossed, I need an algorithm that would find the path indicated by orange squares, not that represented by brown squares.

Notice that, whilst the orange path is also the shortest, that is merely a bonus, not a requirement. I simply need to find the path with minimal changes in direction (achieving a decent balance between length and changes). Also, the algorithm must not require large amounts of memory, as it is to run on an embedded chip.

EDIT: As pointed out by Rudy Velthuis, I haven't exactly explained what I meant by "natural". By natural, I mean a path that isn't too long and only requires the user to change direction a few times.

3 个答案:

答案 0 :(得分:2)

I think you're looking for A* pathfinding. While it will have the side effect of finding the shortest path, it's also going to be natural looking. For a long time it was the gold standard in video games.

Here's an article on the algorithm. Note: you'll have to modify it slightly to allow for diagonal movement.

https://www.raywenderlich.com/4946/introduction-to-a-pathfinding

答案 1 :(得分:2)

Build a graph where each direction change is an edge.

Each cell is represented as 8 vertices. Vertical, horizontal, and diagonal edges are free (cost 0). Others have non-zero cost (or different costs for 45, 90 and 135 degree turns, if you want sharper turns to cost more). Connect adjacent cells in a natural way (N to S, W to E, SW to NE etc). Assign some cost to these edges too (or different costs for vertical/horizontal and diagonal edges, depending on how you define "path length").

Then use A* on the graph. By varying the costs you may tune the balance between "good-looking" and "short".

答案 2 :(得分:2)

A *是要走的路,但你应该考虑到它需要一些黑客来制作"自然"路径。

由于您的地图允许对角线移动,因此启发式可以是:

[]
[recursive]
[recursive, recursive]            // Nothing stops the recursion,
[recursive, recursive, recursive] // so the stack is never going to clear!

即使有了这种启发式,你也会陷入困境:SW,SW,SW,W,W,W的成本与SW,W,SW,W,SW,W相同(看起来更好)。< / p>

有一些快速的黑客可以解决这个问题(打破平局)。

他们在Amit's page(其中包含大量信息和wonderful introduction to A*)中进行了描述。