如果是非递归情况
如果当前点(方格)为出口,则成功退出 (否则)
如果可继续走(向相邻点试探),存在某个可前进 的相邻点(分支)则:
1、将当前点保存,以便回退
2、将相邻点作为当前点继续(该分支)
如果不能前进则:
1、取出最近保存的点,回退作为当前点
2、如果无法取出,则无通路,失败退出
接下来考虑递归情况
#include <iostream>
using namespace std;
typedef struct ElemType{
int x;
int y;
};
typedef struct StackNode { //栈元素结点定义
ElemType data; //结点数据
StackNode* next; //结点链接指针
}*LinkStack; //链式栈
void InitStack(LinkStack& S) { //栈初始化
S = NULL; //栈顶(链头)指针置空
}
int IsEmpty(const LinkStack& S) { //判栈空否
return S == NULL;
}
int Push(LinkStack& S, ElemType& e) { //进栈
StackNode* s = new StackNode;
if (!s) exit(1); //可省略
s->data = e; //结点赋值
s->next = S; S = s; //链入栈顶
return 1;
}
int Pop(LinkStack& S, ElemType& e) { //出栈
if (IsEmpty(S)) return 0;
StackNode* q = S;
S = q->next; e = q->data; //摘下原栈顶
delete q; return 1; //释放原栈顶结点
}
void ReTraverse(const LinkStack& S) {
if (S) {
ReTraverse(S->next);
cout << "("<<S->data.x<<","<<S->data.y<<")"<<endl;
}
}
void Go(ElemType start, ElemType end,int map[][10],LinkStack &S) {
ElemType e; ElemType a;
if (map[start.x][start.y] == 0) {
if (start.x == end.x && start.y == end.y) { Push(S, start); ReTraverse(S); }
else {
map[start.x][start.y] = 1;
Push(S, start);
ElemType startA; startA.x = start.x - 1; startA.y = start.y;
ElemType startL; startL.y = start.y - 1; startL.x = start.x;
ElemType startV; startV.x = start.x + 1; startV.y = start.y;
ElemType startR; startR.y = start.y + 1; startR.x = start.x;
Go(startA, end,map,S);
Go(startL, end, map, S);
Go(startV, end, map, S);
Go(startR, end, map, S);
map[start.x][start.y] = 2;
Pop(S, e);
}
}
}
int main(){
LinkStack S; InitStack(S);
ElemType start; ElemType end;
start.x = 1; start.y = 1;
end.x = 8; end.y = 8;
int map[10][10] =//用二维数组表示地图:9代表墙,0代表通路
{
{ 9,9,9,9,9,9,9,9,9,9 },
{ 9,0,0,9,0,0,0,9,0,9 },
{ 9,0,0,9,0,0,0,9,0,9 },
{ 9,0,0,0,0,9,9,0,0,9 },
{ 9,0,9,9,9,0,0,0,0,9 },
{ 9,0,0,0,9,9,0,0,0,9 },
{ 9,0,9,0,0,0,9,0,9,9 },
{ 9,0,9,9,9,0,9,9,0,9 },
{ 9,9,0,0,0,0,0,0,0,9 },
{ 9,9,9,9,9,9,9,9,9,9 }
};
Go(start, end, map, S);
}
用二维数组表示地图,
Go函数内部设计思路见图:
首先该位置必须为0,即不能为"墙"才能行走,其次如果该位置是终点,则为递归的“出口”,则结束
否则进入递归最小问题:该位置从0标记为1记为走过的路,但因为不能再次走所以不能为0,入栈,之后分别计算上下左右的临近点坐标,挨个调用进行递归,若都失败弹出,则说明进入到了死胡同,标记出栈的位置为2,即为回退的路,与走过的路“1”做区分,然后出栈
完成以上步骤即可得出最终路径: