微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

A *搜索没有选择最佳路线?

如何解决A *搜索没有选择最佳路线?

我正在编写一个A *搜索程序来解决迷宫问题。

该程序的目的是在文本文件mazefile中输入迷宫,并使用A *搜索算法找到从S到G的路径。

该项目当前由4个文件组成,(1)具有类方法代码来操作或使用(2)包含迷宫的文本文件,另一个包含结果文件的文本文件(3)(其中AI已探索)和主要的python脚本(4)。在这里,可以随时将它们复制并粘贴到文件夹中,并查看它们的运行方式。

我认为问题出在A* search.py的第36-48行


while result == "":
    stepsTaken += 1
    explored.append(finger.currentPosition)
    Search()
    try:
        bestNumber = (24**24)**24
        bestIndex = -1
        for i in range(0,len(frontier)):
            if frontierValues[i]+stepsTaken < bestNumber:
                bestNumber = frontierValues[i]+stepsTaken
                print("the chosen one is " + str(frontierValues[i]+stepsTaken))
                bestIndex = i

如果您需要整个程序,则为:

A* search.py

from processtext import importMaze,mazePointer

testObject = importMaze("mazefile")
environment = testObject.processthis()
finger = mazePointer(environment)
frontier = []
frontierValues = []
explored = []
result = ""
stepsTaken = 0
#ADD COORDINATES AFTER CHECKING THE START AND GOAL
def checkClose(coordinate):
    number = 0
    if [coordinate[0],coordinate[1]+1] in explored:
        number+=1
    if [coordinate[0],coordinate[1]-1] in explored:
        number+=1
    if [coordinate[0]+1,coordinate[1]] in explored:
        number+=1
    if [coordinate[0]-1,coordinate[1]] in explored:
        number+=1
    return number
def Search():
    global result
    if len(finger.nearbyFreeSpaces("G")) == 1: #If the goal is bordering this space
        result = finger.nearbyFreeSpaces("G")[0]
    else:
        newPlaces = finger.nearbyFreeSpaces("F") #finds the free spaces bordering
        for i in newPlaces:
            if i in explored: #Skips the ones already visited
                pass
            else:
                frontier.append(i)
                frontierValues.append(finger.finddistance(i))


while result == "":
    stepsTaken += 1
    explored.append(finger.currentPosition)
    Search()
    try:
        bestNumber = (24**24)**24
        bestIndex = -1
        for i in range(0,len(frontier)):
            if frontierValues[i]+stepsTaken < bestNumber:
                bestNumber = frontierValues[i]+stepsTaken
                print("the chosen one is " + str(frontierValues[i]+stepsTaken))
                bestIndex = i

        finger.moveto(frontier[bestIndex])
        frontier.pop(bestIndex)
        frontierValues.pop(bestIndex)
    except:
        pass
def tracingPath():
    initialExplored = explored
    proceed = True
    newExplored = []
    exploredCount = len(initialExplored)
    while proceed == True:
        for i in initialExplored:
            finger.moveto(i)
            if len(finger.nearbyFreeSpaces("G")) == 1:
                pass
            elif (len(finger.nearbyFreeSpaces("S")) == 1) and (len(finger.nearbyFreeSpaces("F")) > 0):
                pass
            elif checkClose(i) > 1:
                pass
            elif checkClose(i) == 1:
                initialExplored.remove(i)
            else:
                print(checkClose(i))

        if len(initialExplored) == exploredCount:
            proceed = False
        else:
            exploredCount = len(initialExplored)
    return initialExplored
exploredArray = []
def recreateMaze(array,newArray):
    for y in range(len(environment)): #Recreates the maze,fills in 'E' in where the AI has visited.
        holder = ""
        for x in range(len(environment[y])):
            if [x,y] in array:
                holder+= "E"
            else:
                holder+= str(environment[y][x])
        newArray.append(holder)
recreateMaze(explored,exploredArray)
tracedFinal = []
recreateMaze(tracingPath(),tracedFinal)

def createResult(mazeList,title,append): #Creating the file
    file = open("resultfile",append)
    string = title + " \n F - Free \n O - Occupied \n S - Starting point \n G - Goal \n E - Path/visited \n (Abdulaziz Albastaki 2020) \n \n (top left coordinate - 0,0) \n Final Solution  \n"
    final = tracingPath()
    for i in tracedFinal:
        string+= "\n" + str(i)
    string+= "\n \n All spots visited \n"
    for i in exploredArray:
        string+= "\n" + str(i)
    string+= "\n \n Original problem \n"
    for i in environment:
        string+= "\n" +str(i)

    file.write(string)
    file.close()

createResult(exploredArray,"A* SEARCH","w")

processtext.py

#code to process the mazefile file.
class importMaze:
    def __init__(self,maze):
        self.fileLines = []
        self.fileName = maze
        self.switch = False
        self.toBeReturned = []
    def processthis(self):
        f = open(self.fileName,"r")
        for x in f:
            self.fileLines.append(x[:-1])
        f.close()
        for i in self.fileLines:
            if self.switch == True:
                if str(i) == "END":
                    self.switch = False
                else:
                    self.toBeReturned.append(i)
            else:
                if str(i) == "START":
                    self.switch = True
        return self.toBeReturned
    
class mazePointer:
    def __init__(self,mazearray):
        self.Sample = mazearray
        self.initialPosition = []
        self.goalLocation = []

        for y in range(0,len(self.Sample)):
           for x in range(0,len(self.Sample[y])):
                if str(self.Sample[y][x]) == "S":
                    self.initialPosition = [x,y]
                elif str(self.Sample[y][x]) == "G":
                    self.goalLocation = [x,y]


        self.currentPosition = self.initialPosition
    def whatIs(self,xcoordinate,ycoordinate):
        return (self.Sample[ycoordinate])[xcoordinate]
    def nearbyFreeSpaces(self,search):
        self.freeSpaces = []
        if self.whatIs(self.currentPosition[0]-1,self.currentPosition[1]) == search:
            self.freeSpaces.append([self.currentPosition[0]-1,self.currentPosition[1]])
        if self.whatIs(self.currentPosition[0]+1,self.currentPosition[1]) == search:
            self.freeSpaces.append([self.currentPosition[0]+1,self.currentPosition[1]])
        if self.whatIs(self.currentPosition[0],self.currentPosition[1]-1) == search:
            self.freeSpaces.append([self.currentPosition[0],self.currentPosition[1]-1])
        if self.whatIs(self.currentPosition[0],self.currentPosition[1]+1) == search:
            self.freeSpaces.append([self.currentPosition[0],self.currentPosition[1]+1])
        return self.freeSpaces

    def moveto(self,position):
        self.currentPosition = position

    def greedBFS(self):
        array = []
        for y in range(0,len(self.Sample)):
            newRow = []
            for x in range(0,len(self.Sample[y])):
                if str(self.Sample[y][x]) == "F":
                    xDigit = (((self.goalLocation[0] - x)**2)**0.5)
                    yDigit = (((self.goalLocation[1] - y)**2)**0.5)
                    newRow.append(str(xDigit+yDigit))
                else:
                    newRow.append(str(self.Sample[y][x]))
            array.append(newRow)
        return array
    def finddistance(self,position):
        return (((self.goalLocation[0] - position[0])**2)**0.5) + (((self.goalLocation[1] - position[1])**2)**0.5)

mazefile

F - Free
O - Occupied
S - Starting point
G - Goal
(Abdulaziz Albastaki 2020)

START
OOOOOOOOOOOOOO
OOFFFFFFFFFFGO
OOFOOOOOOOOOFO
OOFOFFFFFFFOFO
OOFOFOOOOOFOFO
OOFFFOFFFFFOFO
OOOOFOFOOOOOFO
OSFFFOFFFFFFFO
OOOOOOOOOOOOOO
END



Made by Abdulaziz Albastaki in October 2020
You can change the maze and its size however it must
-Respect the key above
-Have ONE Starting point and goal
-The maze must be in between 'START' and 'END'
-The maze MUST be surrounded by occupied space


Sample problems,just copy and and paste it above or create your own:

OOOOOOOOOOOOOOOO
OFFFFFFFFFFFFFGO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OSFFFFFFFFFFFFFO
OOOOOOOOOOOOOOOO

OOOOOOOOOOOOOOOOO
OFOFFFFFOOOFFFOOO
OFFFOOOFOOFFOOOFO
OFOOOOOFOOFOOOOFO
OSFGFFFFFFFFFFFFO
OOOOOOOOOOOOOOOOO

OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOFFFFFFFOOFOOOOOOOOFFFFFFFGOOO
OOFOOOFOFOOOOOOOOOOOOOOOFOOOFOO
OOFOOOOOOOOOOOFOFOOOOOOOFOOOFOO
OOFFFFFFOOOOOOFOFOOOOOOOFOOOFOO
OOFOOFOFOOOOOOFOFOOOOFOOFOOOFFO
OFFOOFFFFFOOFFFFFFFFFFFFFOOOOFO
OFFFFFFFFFOOFOOOOFOFFFOOOFOOOFO
OSOOOOOFOFOOFOOOFOOOOFFFFFOOOFO
OFFFFOOOOFFFFFFFFFFFFFFOOFFFFFO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO

OOOOOOOOOOOOOO
OFOFOFOOOFFOGO
OFOFOFFFOFOOFO
OFFFOFOFFFOOFO
OOFOOFOFOFOOFO
OOFFFFOFOFFFFO
OOOOFOOFOOOOOO
OSFFFOOFFFFFFO
OOOOOOOOOOOOOO

OOOOOOOOOOOOOO
OOFFFFFFFFFFGO
OOFOOOOOOOOOFO
OOFOFFFFFFFOFO
OOFOFOOOOOFOFO
OOFFFOFFFFFOFO
OOOOFOFOOOOOFO
OSFFFOFFFFFFFO
OOOOOOOOOOOOOO

resultfile

A* SEARCH 
 F - Free 
 O - Occupied 
 S - Starting point 
 G - Goal 
 E - Path/visited 
 (Abdulaziz Albastaki 2020) 
 
 (top left coordinate - 0,0) 
 Final Solution  

OOOOOOOOOOOOOO
OOFFFFFFFFFFGO
OOFOOOOOOOOOEO
OOFOEEEEEEEOEO
OOFOEOOOOOEOEO
OOFFEOEEEEEOEO
OOOOEOEOOOOOEO
OSEEEOEEEEEEEO
OOOOOOOOOOOOOO
 
 All spots visited 

OOOOOOOOOOOOOO
OOFFFFFFFFFFGO
OOFOOOOOOOOOEO
OOFOEEEEEEEOEO
OOFOEOOOOOEOEO
OOFFEOEEEEEOEO
OOOOEOEOOOOOEO
OEEEEOEEEEEEEO
OOOOOOOOOOOOOO
 
 Original problem 

OOOOOOOOOOOOOO
OOFFFFFFFFFFGO
OOFOOOOOOOOOFO
OOFOFFFFFFFOFO
OOFOFOOOOOFOFO
OOFFFOFFFFFOFO
OOOOFOFOOOOOFO
OSFFFOFFFFFFFO
OOOOOOOOOOOOOO

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。