简体   繁体   English

穿过二维阵列中障碍物(地雷)的最短路径(C编程)

[英]Shortest path through obstacles (mines) in a 2D array (C programming)

I have a problem with a C program, where a 2D array with mines is given (mines = array fields set to 1). 我在C程序中遇到问题,其中给出了带有地雷的2D数组(mines =设置为1的数组字段)。 I need to find the shortest path from (0,0) to (x-1,y-1), and you can move only in 4 directions (up, down, left, right). 我需要找到从(0,0)到(x-1,y-1)的最短路径,并且您只能在4个方向(上,下,左,右)移动。

Do you have any ideas, what the algorithm should look like to keep the program fairly simple? 您有什么想法,算法应使程序保持相当简单?

A* and Dijkstra are more complicated than you need for this problem because, in the graph you are searching, all edges (steps between grid squares) have weight 1. A *和Dijkstra比解决此问题所需的更为复杂,因为在要搜索的图形中,所有边缘(网格正方形之间的步长)的权重均为1。

Just use Breadth First Search: 只需使用广度优先搜索:

Let Q be a queue of (x,y) pairs
Let V be a set of (x,y) pairs.
Add the start point (x0,y0) to Q.
While Q is not empty
  H = Q.get_head
  for each neighbor pair N of H in the grid
    if N is not in V
      add N to V
      if N is the goal
        Return N. The path is the chain of N.prev references
      N.prev = H
      Q.add_to_tail(N)
Return "goal could not be reached"

Use Dijikstra's Algorithm. 使用Dijikstra的算法。 It will solve the problem in O(x*y) time 它将解决O(x * y)时间的问题

You can also try A-Star (see wikipedia entry ). 您也可以尝试A-Star(请参阅Wikipedia条目 )。 It is an extension of Dijkstra's algorithm, it's worst-case running time is O(|E|), but can be improved by using heuristics. 它是Dijkstra算法的扩展,最坏的运行时间是O(| E |),但可以使用启发式方法进行改进。 A-Star will find the lowest cost path through the area, and in your case the cost that you will be using will be the total distance traveled. A-Star会找到通过该区域的最低成本路径,在您这种情况下,您将使用的成本将是总行驶距离。

Given your limitation on movement, you would probably be best served by using a 'manhattan-distance' heuristic. 考虑到您的运动限制,最好使用“曼哈顿距离”启发式方法为您服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM