Why Wont Maze Solver Code Work
Solution 1:
No claims as to whether this is faster than the other answer, but if you want to return True/False if you have found the exit, then you can maintain a boolean for each of the recursive calls.
(Also, your print_grid
method can be shorter)
def print_grid():
print "\n".join(' '.join(row) forrowin grid)
Anyways, here are the modifications that I made to the program.
defmain(x, y):
# Check going out of boundsif y < 0or y >= len(grid):
returnFalseif x < 0or x >= len(grid[y]):
returnFalseif grid[x][y] == "E":
print"Found exit at %d %d" % (x, y)
returnTrueelif grid[x][y] == "#":
print"Found wall at %d %d" % (x, y)
returnFalseelif grid[x][y] == " "or grid[x][y] == "T":
print"Found empty at %d %d" % (x, y)
grid[x][y] = "x"# no return, we want to continue searchingelse: # catch invalid charactersreturnFalse
found = False# "Bubble-up" the results from searching for the exit # Also limit the search space by keeping track if the exit was foundif y < len(grid)-1andnot found:
found = main(x, y + 1)
if y > 0andnot found:
found = main(x, y - 1)
if x < len(grid[x])-1andnot found:
found = main(x + 1, y)
if x > 0andnot found:
found = main(x - 1, y)
return found
Solution 2:
return is the end point of a function, in your code you need to remove the return true because it is causing your program to exit prematurely. Adsitionally, you need an if case to deal with the cells that have been visited already (set to 'x').
I played around with it for a minute, the final result looks like this:
def main(x, y):
if grid[x][y] == " "or grid[x][y] == "T":
print"Found empty at %d %d" % (x, y)
grid[x][y] = "x"
elif grid[x][y] == "#":
print"Found wall at %d %d" % (x, y)
return
elif grid[x][y] == "E":
print"Found exit at %d %d" % (x, y)
returnelse: returnify < len(grid)-1:
main(x, y + 1)
ify > 0:
main(x, y - 1)
ifx < len(grid[x])-1:
main(x + 1, y)
ifx > 0:
main(x - 1, y)
Note that this code finds and visits every cell in the grid, and continues even after the end is found. If you want something to actually solve your maze and give you the steps necessary, you can make a few modifications to this code so that it stores the path you take. You can also research Breadth-First-Search as this is pretty much what you are using here.
Post a Comment for "Why Wont Maze Solver Code Work"