简体   繁体   English

如何在0和1的矩阵中找到两个随机点之间的路径

[英]How to find the path between two random points in a matrix of 0 and 1

I'm trying to create a method in which I get a square matrix of 0 and 1, where 1 can walk and 0 are the obstacles that must be circumvented, in addition to the random start and end points.我正在尝试创建一种方法,在该方法中我得到一个 0 和 1 的方阵,其中 1 可以行走,0 是必须绕过的障碍,除了随机起点和终点。

I needed this method to provide me with a sense of the path that should be followed, such as:我需要这种方法来让我了解应该遵循的路径,例如:

例子

Where the return would be "right, up, right, right, down, right" and "down, right, down, right, right, up, right, up" respectively.返回将分别为“右、上、右、右、下、右”和“下、右、下、右、右、上、右、上”。

Thanks谢谢

One way could be to write a function which checks if the current field is the destination field and call this function recursively for all neighbors.一种方法是编写一个 function 检查当前字段是否为目标字段,并为所有邻居递归调用此 function。 In each recursion step you add the direction and return the full path when you are finished.在每个递归步骤中,您添加方向并在完成后返回完整路径。

dest_x = 4
dest_y = 1
visited = []

def next (path, x, y):
    visited.append ([x, y])
    
    # obstacle
    if matrix[x][y] == 0:
        return None
    
    # found destination
    if x == dest_x and y == dest_y:
        return path
    
    for i in [{'x': x - 1, 'y': y, 'direction': 'left'},
              {'x': x + 1, 'y': y, 'direction': 'right'},
              {'x': x, 'y': y - 1, 'direction': 'up'},
              {'x': x, 'y': y + 1, 'direction': 'down'}]:
        if [i['x'], i['y']] not in visited and i['x'] >= 0 and i['x'] < len(matrix) and i['y'] >= 0 and i['y'] < len(matrix[x]):
            n = next (path + [i['direction']], i['x'], i['y'])
            if n != None:
                return n
    
    
    

matrix = [[1,1,1,1],
          [1,1,1,1],
          [1,0,0,1],
          [1,1,1,1],
          [1,1,1,1]]

print (next ([], 0, 1))

This will find one way if there is one.如果有一种方法,这将找到一种方法。 In case you need the shortest way you can store the path in an array when you reach the destination instead of returning it.如果您需要最短的方法,您可以在到达目的地时将路径存储在数组中,而不是返回它。 When all paths are discovered you can print the path with minimum length发现所有路径后,您可以打印最小长度的路径

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

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