| Arevos |
Dec 17th, 2006 9:18 AM |
Quote:
Originally Posted by kyndig
(Post 121270)
I see what you are saying, you could possibly, add some code to check another step ahead, and see if that 'branch' is a dead end, if it is then dont add that as a step.
|
No need. Seeing how old this post is, I don't suppose it would hurt for me to give a more exact answer to the problem. Essentially, with each recursive step you'd pass in a variable that would record the "depth" of that step. So instead of "solving(r+1,c)" you'd use, "solving(r+1,c,depth+1)". Then, when you find the exit, just return the depth. If the exit isn't found, return 0 or -1.
In Python, you'd do something like this:
:
def load_maze(filename): file = open(filename) length = file.readline() maze = [[int(x) for x in line.split()] for line in file] file.close() return maze def solve_maze(maze): def explore(x, y, depth): if len(maze) == (y + 1) and len(maze[y]) == (x + 1): return depth try: value = maze[y][x] except IndexError: return 0 if value == 0: return 0 return explore(x + 1, y, depth + 1) or explore(x - 1, y, depth + 1) or explore(x, y + 1, depth + 1) or explore(x, y - 1, depth + 1) return explore(0, 0, 1) solution = solve_maze(load_maze("recursion.txt")) if solution: print "End of maze reached in %d steps" % solution else: print "No solution"
|