我有一個程序,讀取從文件中的迷宮,並把它變成一個二維數組和導航的方式,雖然使用遞歸,並放置一個P到處它一直和V每其中兩次。在我的算法的某個地方有一個問題,導致迷宮只有Vs.我已經輸入了許多println
語句來嘗試調試該問題。我是Java的新手,我可能錯過了一些明顯的東西,但我無法找到我生活中的問題。迷宮遍歷算法遞歸
迷宮代碼:
public static boolean goNorth(){
boolean success;
if(maze[currCol][currRow - 1] == CLEAR){
currRow = currRow - 1;
maze[currCol][currRow] = PATH;
if (maze[currCol][currRow] == maze[finishCol][finishRow]){
success = true;
} else {
success = goNorth();
if(!success){
success = goWest();
if(!success){
success = goEast();
if(!success){
maze[currCol][currRow] = VISITED;
currRow = currRow + 1;
}
}
}
}
} else {
success = false;
}
return success;
}
public static boolean goWest(){
boolean success;
if(maze[currCol - 1][currRow] == CLEAR){
currCol = currCol - 1;
maze[currCol][currRow] = PATH;
if (maze[currCol][currRow] == FINISH){
success = true;
} else {
success = goWest();
if(!success){
success = goSouth();
if(!success){
success = goNorth();
if(!success){
maze[currCol][currRow] = VISITED;
currCol = currCol + 1;
}
}
}
}
} else {
success = false;
}
return success;
}
public static boolean goEast(){
boolean success;
if(maze[currCol + 1][currRow] == CLEAR){
currCol = currCol + 1;
maze[currCol][currRow] = PATH;
if (maze[currCol][currRow] == FINISH){
success = true;
} else {
success = goEast();
if(!success){
success = goNorth();
if(!success){
success = goSouth();
if(!success){
maze[currCol][currRow] = VISITED;
currCol = currCol - 1;
}
}
}
}
} else {
success = false;
}
return success;
}
public static boolean goSouth(){
boolean success;
if(maze[currCol][currRow + 1] == CLEAR){
currRow = currRow + 1;
maze[currCol][currRow] = PATH;
if (maze[currCol][currRow + 1] == FINISH){
success = true;
} else {
success = goSouth();
if(!success){
success = goEast();
if(!success){
success = goWest();
if(!success){
maze[currCol][currRow] = VISITED;
currRow = currRow - 1;
}
}
}
}
} else {
success = false;
}
return success;
}
所需的輸出:
xxxxxxxxxxxxxxxxxxFx
xVVVVVxPPPPPPPxxxxPx
xVxxxxxPxxxxxPPPxxPx
xVxxxxxPxxxxxxxPxxPx
xVVVVVVPPPPPPxxPxxPx
xVxxxxxxxxxxPxxPPPPx
xxxxxxxxxxxxSxxxxxxx
輸出我得到:
xxxxxxxxxxxxxxxxxxVx
xVVVVVxVVVVVVVxxxxVx
xVxxxxxVxxxxxVVVxxVx
xVxxxxxVxxxxxxxVxxVx
xVVVVVVVVVVVVxxVxxVx
xVxxxxxxxxxxVxxVVVVx
xxxxxxxxxxxxSxxxxxxx
KyleM的調試建議很好。另外,你已經寫了4個非常非常相似的函數。有什麼方法可以重寫代碼以減少重複嗎?除了讓你的代碼更易於閱讀和維護之外,像這樣凝結你的代碼常常會使錯誤更加明顯。 – 2013-04-26 03:52:58