穿过迷宫时的 Dijkstra 算法

问题描述 投票:0回答:0

尝试使用 Dijkstra 算法在迷宫中导航,但我遇到了不知道如何修复的错误。在尝试修复所述错误后,它首先抛出一个错误,指出将“.any()”放在 if 语句的末尾 -

if Maze[tuple(currentCoords)] == "_".any():

在我这样做之后,它又抛出了另一个错误,那就是-

    if Maze[tuple(currentCoords)] == "_".any():
AttributeError: 'str' object has no attribute 'any'

现在我真的不知道该怎么做,代码应该在迷宫中移动,同时检查下一个可用的方块。

这是我的代码

import time
import numpy as np

# The 7 by 7 grid provided. X is the starting square,
# _ represents a square, Y is the finishing square
# and Z is an obstacle.
Maze = np.array([
    "X", "_", "_", "_", "_", "Z", "_",
    "_", "Z", "Z", "Z", "_", "_", "_",
    "_", "Z", "_", "_", "_", "_", "Z",
    "_", "_", "_", "_", "_", "_", "_",
    "_", "_", "Z", "_", "Z", "Z", "_",
    "_", "_", "Z", "_", "Z", "_", "_",
    "_", "_", "Z", "_", "_", "_", "Y"
])

# Reshape the 1D array into a 2D 7x7 grid
Maze = Maze.reshape((7, 7))

CurrentValue = "Y"
i = 0

# If not on the starting square, the robot will move to
# a new square and check if it is an obstacle or a new 
# square.

def check_next_coordinates(X, Y):
    if 0 <= X < 7 and 0 <= Y < 7:
        return Maze[X, Y] != "Z"
    return False

while CurrentValue != "X":
    currentCoords = np.argwhere(Maze == CurrentValue)
    print("Current Coordinates:", currentCoords[-1])
    time.sleep (1)
    print(Maze)

    # If the new square is an empty space, mark it as the current value + 1.
    print(Maze[tuple(currentCoords[-1])])
    if Maze[tuple(currentCoords)] == "_".any():

        Maze[tuple(currentCoords[-1])] = str(int(CurrentValue) + 1)
    elif Maze[tuple(currentCoords[-1])] == "X":
        print("Maze:", Maze)
        CurrentValue = "X"

    X = currentCoords[-1]
    Y = currentCoords[-7]

    # Check the left space
    left_x, left_y = X, Y - 1
    if check_next_coordinates(left_x, left_y):
        if Maze[left_x, left_y] == "_":
            Maze[left_x, left_y] = str(int(CurrentValue) + 1)
        elif Maze[left_x, left_y] == "X":
            print("Left space is available")
            CurrentValue = "X"

    # Check the above space
    above_X, above_Y = X - 1, Y
    if check_next_coordinates(above_X, above_Y):
        if Maze[above_X, above_Y] == "_":
            Maze[above_X, above_Y] = str(int(CurrentValue) + 1)
        elif Maze[above_X, above_Y] == "X":
            print("Space above is available")
            CurrentValue = "X"

    print (Maze)

是否需要在代码中添加或更改任何内容,因为我真的不知道自己在做什么,因为我对编码相当陌生。 感谢您的所有帮助。

python dijkstra robotics
© www.soinside.com 2019 - 2024. All rights reserved.