简体   繁体   中英

How to find shortest path between two points in a given output of DFS

I have a project involving drawing with a robot hand that can only move on the x,y coordinates. For a given binary image, I've used DFS to explore it. The DFS algorithm returns an array of points that DFS has explored. That array is the path. It works fine.

The problem is that there are jumps in that path(the DFS algorithm returns the path with jumps). For example:

00000000000
00001000000
00001000000
01111000000
00001000000
00001000000
00000000000

The path returned by DFS, is as intended, something like this: (3,1)->(3,2)->(3,3)->(3,4)->(2,4)-> (1,4)->(4,4) ->(5,4) My intention is to not have a jump in this path, so I want to create a function/method that has as input this path(the one with jumps, which is the output of DFS) And outputs another path that is completed with routes from one jump point to another. For the given example the path should be this: (3,1)->(3,2)->(3,3)->(3,4)->(2,4)-> (1,4)->(2,4)->(3,4)->(4,4) ->(5,4)

Is there a good way to do this?

I've tried something but for a complex image it has huge problems(for an output of DFS of only 2000 points, when I try to complete the missing routes, i get at least 10 million points as output path).

The algorithm is intended to work this way: I iterate through path, when I see a jump point between the current point and the last one, i go back the way I came from until I find it.

Any ideas? Thank you for your time!

Later edit: Thank you for your time! I figured it out that i'd better use bfs to find the shortest path back, since i actually need it for the robot to take as few steps as possible. It isn't very efficient(it takes about 5 seconds to process a 640x480 binary image) but it works very well(in the end i get about double the number of points that DFS outputs, which I find reasonable).

Your solution is the best if you decide to use a DFS to find the path, but the problem of finding the shortest path to plot points by a robot arm, like you describe, is NP hard, since it's a variant of the traveling salesman problem.

That being said, the fastest algorithms solving this problem can be found by searching for plotter algorithms or reading graph theory books.

These algorithms use similar ideas as the solutions to the traveling salesman, where Euler tours and matchings are used to find the shortest path.

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