Frage

Hello I am trying to write a maze solving program in python using the waveform algorithm (explained here). I am using nested loops to loop through a matrix and change the numbers like in this animated gif.

However it only seems to be looping through the first row of my matrix and not moving on to the rest. I have been staring at this thing for quite a while and I'm hoping that getting some fresh eyes on it will help.

Thanks, Logan

floorMap = [[000,000,000,000,000,999,999,999,999,999],
           [000,000,999,000,999,000,000,000,999,999],
           [000,000,999,000,999,000,000,000,999,999],
           [000,000,000,000,999,000,000,000,999,999],
           [999,000,000,000,999,000,999,999,999,999],
           [999,000,000,000,000,000,999,000,000,999],
           [999,000,000,000,999,999,999,000,000,999],
           [999,000,999,000,000,000,999,000,000,999],
           [999,000,999,999,999,000,000,000,000,999],
           [999,999,999,999,999,999,999,999,000,000]]
robotX=0
robotY=0

goalX=9
goalY=9

currentNum=0

wall=999
uncalculated=000

floorMap[robotX][robotY]=1


def changeSurroundings(X, Y):
    #left
    if(floorMap[X-1][Y]==000):
        floorMap[X-1][Y]=currentNum   
    #right 
    if(floorMap[X+1][Y]==000):
        floorMap[X+1][Y]=currentNum  
    #up
    if(floorMap[X][Y-1]==000):
        floorMap[X][Y-1]=currentNum  
    #down
    if(floorMap[X][Y+1]==000):
        floorMap[X][Y+1]=currentNum    

def printMap():
    i=0
    while(i<len(floorMap)):
        print floorMap[i]
        print ""
        i+=1
    print ""
    print ""



#------------------THIS IS WHERE THE PROBLEM IS--------------

while(floorMap[goalX][goalY]==0):
    x=0
    y=0
    while(x<len(floorMap[0])):
        while(y<len(floorMap)):
            if(floorMap[x][y] > 000 and floorMap[x][y] < 999):
                currentNum=floorMap[x][y]+1
                changeSurroundings(x,y)
                printMap()

            y+=1
        x+=1
War es hilfreich?

Lösung

x=0
y=0
while(x<len(floorMap[0])):
    while(y<len(floorMap)):
        ...
        y+=1
    x+=1

The problem here is that once the inner loop has exhausted the y values, it will be exhausted until the outer loop has completed, since you don't reset y for each inner loop.

Simply move the y=0 line into the outer loop:

x=0
while(x<len(floorMap[0])):
    y=0
    while(y<len(floorMap)):
        ...
        y+=1
    x+=1
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top