简体   繁体   中英

Shortest Path Algorithm : Uniform distances from one point to adjacent points

I am trying to develop an algorithm wherein I have a Location Class. In each class, I create a list of its adjacent Locations. I want to know, how can I get the shortest path from one Location to another. I am trying to look for different algorithms but it seems that they doesn't answer my problem.

For example, I have a point A and I want to go to point B,

A - - C - - H - - J
      |
      F- - K- -B 

My idea for this is if B is in the List of adjacent locations of A, then that is the shortest path. If not, it should search the adjacent locations of the adjacent locations of A. But I do not know how to implement this in code or if it is a good algorithm. I also want to display A - C - F - K - B as the route for the shortest path. I am also developing this one on j2me so I am a bit limited on the java features that I can use. If anyone can help me, it will be much appreciated. Thanks

You are on the right track. What you describe is the start of BFS . BFS is a shortest-path algorithm that is both optimal [finds the shortest path] and complete [always finds a path if one exist] for unweighted graph - so it is probably the right choice.

BFS works on graphs. In here your graph is G = (V,E) such that V = {all locations} [the nodes/vertices/locations] and E = {(u,v),(v,u) | u and v are neighbors} E = {(u,v),(v,u) | u and v are neighbors} [the edges/links/neighbors]

The idea of BFS is simpilar to what you are suggesting: first check if the starting node is also the target. Then check if one of the neighbors of the starting node is the target, then search for their neighbors....

Regarding getting the actual path from BFS: have a look at this post .
The idea is to maintain a map - for each node [location] - the map will indicate how did you get there? which node discovered it? After the BFS finished - follow the map from target to source, and you get the actual path [reversed of course]. The link provided gives more details about this idea.

Your problem is known in the computing world as a graph search problem, looking for the shortest path between two nodes. Graphs here are not the x and y axis graphs from math, but Nodes (or Locations in your example) connected by edges.

Dijkstra's algorithm is the most commonly used to find the shortest path between two nodes, and for your use case it is simplified slightly because the edges in your scenario all have a weight (or cost) of one. An implementation of this is available in JGraphT , though I'm not sure how easy that is to include in a J2ME environment.

看看A*算法Dijkstra的寻路算法。

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