用棧實現迷宮求解

嚴書上迷宮問題求解,講了棧的用途,能夠存放過程數值。本身實現頗有難度(好像圖的深度遍歷也行,有什麼聯繫呢?)。spa

核心代碼以下:code

 1 Status MazePath(PosType start, PosType end) 
 2 { 
 3   
 4   PosType curpos=start; 
 5   SqStack S; 
 6   SElemType e; 
 7   InitStack(S); 
 8   do
 9   { if(Pass(curpos)) 
10     { FootPrint(curpos); 
11       e.ord=curstep; 
12       e.seat=curpos; 
13       e.di=0; 
14       Push(S, e); 
15       curstep++; 
16       if(curpos.x==end.x && curpos.y==end.y) 
17         return TRUE;
18       NextPos(curpos, e.di); 
19     }
20     else 
21     { if(!StackEmpty(S)) 
22       { Pop(S, e); 
23         curstep--; 
24         while(e.di==3 && !StackEmpty(S)) 
25         { MarkPrint(e.seat); 
26           Pop(S, e); 
27           curstep--; 
28         }
29         if(e.di<3) 
30         { e.di++; 
31           Push(S, e); 
32           curstep++; 
33           curpos=e.seat; 
34           NextPos(curpos,e.di);
35         }
36       }
37     }
38   }while(!StackEmpty(S));
39   return FALSE;
40 }

相關文章
相關標籤/搜索