本帖最後由 smoke_cheese 於 2014-11-7 12:22 編輯
Actually the question already told you how to solve it.
"Write a program to find a path in a maze using recursion."
"One simple way to find a path is at each step: try moving along one of the allowable directions and try another direction if that one fails."
The top left (start) cell is (0,0) and the bottom right (exit) cell is (n,n).
You want to write a function to check if cell (x,y) can reach the exit.
You know:
Check(x,y) is false if cell (x,y) is blocked.
Check(n,n) is true if cell (n,n) is open.
"moving along one of the allowable directions"
"Each move is either horizontally (left or right) or vertically (up or down) but never diagonally."
Check(x,y) is true if cell (x,y) is open and (
Check(x-1,y) is true or
Check(x+1,y) is true or
Check(x,y-1) is true or
Check(x,y+1) is true )
So you write Check(x,y) to call those four functions above recursively.
Then you can just call Check(0,0) from your main program. If Check(0,0) is true then there is a solution to the maze.
Notes:
1. You also don't want to go back the direction you came so you also need to pass the direction you're coming from to Check(x,y), or you'll have to mark cells you've visited and not visit them twice (this would solve the problem of going in circles mentioned in the question as well).
2. The question also ask you to record the path taken. So you pass the current path you have to Check(x,y) also and append the new direction to the path depending on which of the four direction returns true, then return the new path to the caller. |