我正在寫迷宮的求解路徑解[30] [30] 我在路徑查找函數中使用了回溯法; 這裏是僞代碼:C中的回溯迷宮求解器
bool find_path(myMap,myVisited,myPath,v,h)
- 找到起點
[v,h]
然後運行find_path
功能點 - 所訪問
- 終止條件1紀念室:如果
h=29
,對道路標記,然後返回true - 遞歸部分:搜索8個鄰居:西,西北,北,東北,東,東南,南,西南。 檢查房間是否可以訪問,然後調用find_path函數,如果返回true,則在查找路徑上標記。
- 終止條件2:返回false。
當我運行它時,它總是給出分段錯誤。我曾嘗試過不同的方法,但都給出相同的錯誤? 輸出應該是這樣的形象: 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;}
通過調試器運行你的代碼,你應該找到錯誤。 – Haris
試着用一個3×3的小迷宮來運行它,它工作嗎?嘗試調試它。 什麼行壓碎? – OopsUser
'if(v> = 0 || v <30||h> = 0 || h <30 || myMap [v] [h]!='。'|| myVisited [v] [h] =='*')return true ;'你很困惑,並且或者在這裏。 – wildplasser