有些东西想象容易,但是实际做起来真的并不像想象中容易。就像迷宫问题,看起来很容易,不就是用站保存路径,搜索嘛。可是实现起来并不像想象中那么快,10多分钟就可以写一个能准确运行的代码。
以前上数据结构的时候就觉得迷宫问题其实算法原理挺简单的,当时细研究的时候就有点糊涂,转不过来弯。今天偶有兴致,看到这个问题,就实现了一把,锻炼一下编码与调试的能力,结果花费了将近一个小时的时间才顺利调试通过,正确运行,真是惭愧。其中忽略的一点就是对走过的路径没有标记,导致死循环出现。下面直接贴源码,希望以后注意这些细小的问题,并多动手实现一下。
#include <iostream>
#include <stack>
using namespace std;
struct pathnode
{
int x;
int y;
int direct;
};
void printstack(stack<pathnode> s)
{
if(s.size() > 1)
{
pathnode current = s.top();
s.pop();
printstack(s);
cout<<"axis:"<<current.x<<","<<current.y<<"/tdirection:"<<current.direct<<endl;
}
else
{
pathnode current = s.top();
cout<<"axis:"<<current.x<<","<<current.y<<"/tdirection:"<<current.direct<<endl;
}
}
int main()
{
int maze[10][10] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int mark[10][10] = {
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1}
};
int startx = 1,starty = 1;
int endx = 8,endy = 8;
stack<pathnode> s;
pathnode pn;
pn.x = startx;
pn.y = starty;
pn.direct = 1;
s.push(pn);
mark[startx][starty] = 0;
while(!s.empty())
{
pathnode current = s.top();
if(current.x == endx && current.y == endy)
{
break;
}
if(maze[current.x][current.y] == 1)
{
s.pop();
}
else
{
while(current.direct <= 4)
{
pathnode next = current;
switch(current.direct)
{
case 1:
next.y = next.y + 1;
break;
case 2:
next.x = next.x + 1;
break;
case 3:
next.y = next.y - 1;
break;
case 4:
next.x = next.x - 1;
break;
}
if(maze[next.x][next.y] == 0 && mark[next.x][next.y] == 1)
{
s.pop();
s.push(current);
next.direct = 1;
s.push(next);
mark[next.x][next.y] = 0;
break;
}
++current.direct;
}
if(current.direct > 4)
{
s.pop();
}
}
}
cout<<s.size()<<endl;
printstack(s);
return 0;
}