![](/img/trans.png)
[英]Recursive backtracking alogrithm for a maze solver in C is not back tracking and gets stuck
[英]Backtracking maze solver in C
我正在為迷宮[30] [30]編寫查找路徑解決方案。在路徑查找功能中使用了回溯; 這是偽代碼:
bool find_path(myMap,myVisited,myPath,v,h)
[v,h]
然后對該點運行find_path
函數 h=29
,在路徑上標記,然后返回true 當我運行它時,它總是會給出細分錯誤。 我嘗試了不同的方法,但是都給出了相同的錯誤? 輸出應如下圖所示: http : //postimg.org/image/cd8unwet5/這是我的代碼:
// myMap ='.' is a block on map
//myVisited ='*' room visited
bool isSafe(char myMap[30][30], char myVisited[30][30], int v,int h){
if(v>=0||v<30||h>=0||h<30||myMap[v][h]!='.'||myVisited[v][h]=='*')return true;
return false;}
//3 map
//myMap contain the maze
//myVisited use to mark room visited
//myPath is final path.
bool find_path(char myMap[30][30],char myVisited[30][30],char myPath[30][30], int v,int h){
//giving h=-1 and v=-1 , find starting point.
if(h==-1&&v==-1){
h=h+1;
for (v=0;v<30;v++){
if(myMap[v][h]!='.'&& h==0) {find_path(myMap,myVisited,myPath,v,h);}
}
}
myVisited[v][h]='*'; //mark room as visited.
if(h==29){ //stop when column is 29 and mark on path
myPath[v][h]='*';
return true;}
if(isSafe(myMap,myVisited,v,h-1)==true){ //if room is okie to access
if(find_path(myMap,myVisited,myPath,v,h-1)==true){ // there is way out
myPath[v][h]='*'; //mark on myPath
}
}
//.......same code for other room
if(isSafe(myMap,myVisited,v,h+1)==true){ //if room is okie to access
if(find_path(myMap,myVisited,myPath,v,h+1)==true){ // there is way out
myPath[v][h]='*'; //mark on myPath
}
}
if(isSafe(myMap,myVisited,v-1,h)==true){ //if room is okie to access
if(find_path(myMap,myVisited,myPath,v-1,h)==true){ // there is way out
myPath[v][h]='*'; //mark on myPath
}
}
if(isSafe(myMap,myVisited,v+1,h)==true){ //if room is okie to access
if(find_path(myMap,myVisited,myPath,v+1,h)==true){ // there is way out
myPath[v][h]='*'; //mark on myPath
}
}
if(isSafe(myMap,myVisited,v+1,h-1)==true){ //if room is okie to access
if(find_path(myMap,myVisited,myPath,v,h-1)==true){ // there is way out
myPath[v][h]='*'; //mark on myPath
}
}
if(isSafe(myMap,myVisited,v-1,h-1)==true){ //if room is okie to access
if(find_path(myMap,myVisited,myPath,v-1,h-1)==true){ // there is way out
myPath[v][h]='*'; //mark on myPath
}
}
if(isSafe(myMap,myVisited,v-1,h+1)==true){ //if room is okie to access
if(find_path(myMap,myVisited,myPath,v-1,h+1)==true){ // there is way out
myPath[v][h]='*'; //mark on myPath
}
}
myVisited[v][h]='.';
return false;//back track
return false;}
嘗試使用這個
bool isSafe( char myMap[ 30 ][ 30 ], char myVisited[ 30 ][ 30 ], int v,int h ) {
bool ret_val = true;
ret_val = ( v >= 0 ) && ( v < 30 ) && ( h >= 0 ) && ( h > 30 ) && ( myMap[ v ][ h ] != '.' ) && ( myVisited[ v ][ h ] != '*' );
return ret_val;
}
編輯:謝謝@NiBZ-似乎更混亂,但現在不會導致段錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.