简体   繁体   中英

Shortest Path(s) in unweighted 2D array. How to show steps/directions taken during BFS

What I'm trying to do in this algorithm is, given a 2D array, find the shortest path from a given start point (S) and a given endpoint (D)--bearing in mind that some elements in the array (*) are considered obstacles. Normally, I'd perform the typical BFS and return the distance of the shortest path, but there's a bit of an added wrinkle. I need to show the shortest path(s) taken by replacing a traversed element with the cardinal direction (North, South, East, or West. abbreviated to n,s,e,w respectively) that the path takes to the destination. In the event of multiple shortest paths, where you could go EITHER south or east to reach the goal, the element would be filled with the combination of cardinal direction ie "se" as shown in the second picture. NOTE that this does not mean SouthEast as no diagonal traversals are allowed. I'm familiar with using BFS in algorithms, but I'm a bit stuck as to how I mark the path(s) taken with the directions included. I'm not necessarily looking for a full-blown algorithm in response to this question, but more an answer in pseudo-code to get me on the right track. The first picture is of a sample input Array, and the second picture is of the "solution" to said input Array. TL:DR I'm asking for advice as to how to go about keeping track of the directions taken through the grid while performing BFS Any and all help/feedback is greatly appreciated, and thank you in advance!

示例输入二维数组

示例输出二维数组

You can tag each node (array entry) with one piece of meta-data: the shortest path-length. This can be done with various algorithms , but BFS basically gets you there. Every node that is reachable should have a number.

From your example, S would be a zero (zero steps to get from S to S) and D is a 16 (16 steps to get from S to D). Now you have everything you need.

You can now:

1: pick the ending node (d=16)

2: search its immediate vicinity (n,e,s,w)

3: if nodes have d-1, write (append) a letter depending on which of the four directions in its vicinity you were looking at. Ignore other nodes.

4: Pick all nodes with d-1 and at least 1 letter

5: Foreach picked node, do step 2 - 3

6: if(d-1 > 0) d = d-1 and do step 4 - 5

That's the rough shape of an algorithm that'll do it. It would work for D in any location. If, however, you move S, you need to re-tag each node.

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