大家应该都有往袋子里装东西的经历,在往袋子里装满东西之后,当我们去取的时候,总是先从最后放进去的东西的地方去取。也就是后进先出(FILO)。虽然栈的单向性用起来会没有链表那样可以在任意位置对数据进行操作,但是正因为如此栈也带来了很大的方便。
1:设定寻找的方向,可以使用一个判断语句;判断起始位置周围哪个地方有路就将该位置的坐标加入到栈中,并将该位置标记(将改位置值改为2,既将走过的位置标记为2)
//迷宫求解的方法类
//功能:通过findPath() 方法实现对路径的查找
// 通过printPath()方法将路径打印出来
#include "PathStack.h"
#include <iostream>
using namespace std;
class MazeSolveMethod
{
private:
static int maze[10][10];//存放迷宫数据
PathStack<int> pathStack;//定义栈
public:
MazeSolveMethod():pathStack(100){
}
~MazeSolveMethod(){ }
void findPath(int startX,int startY);
void printPath() const;
};
int MazeSolveMethod::maze[10][10] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,1,0,0,0,0,1},
{1,0,0,0,1,0,1,0,0,1},
{1,0,1,0,0,0,1,1,0,1},
{1,0,1,0,0,0,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,1,1,1,1,0,0,0,1,1},
{1,1,1,1,1,1,1,0,0,1},
{1,1,1,1,1,1,1,1,1,1},
};
void MazeSolveMethod::findPath(int startX,int startY){
int x = startX;
int y = startY;
pathStack.push(x);
pathStack.push(y);
maze[x][y] = 2;
cout<<"进入方法!"<<endl;
while(true){
if(maze[x-1][y] == 0){
pathStack.push(--x);
pathStack.push(y);
maze[x][y] = 2;
}else if(maze[x][y-1] == 0){
pathStack.push(x);
pathStack.push(--y);
maze[x][y] = 2;
}else if(maze[x][y+1] == 0){
pathStack.push(x);
pathStack.push(++y);
maze[x][y] = 2;
}else if(maze[x+1][y] == 0){
pathStack.push(++x);
pathStack.push(y);
maze[x][y] = 2;
}
if(maze[x-1][y] != 0 && maze[x][y+1] != 0 && maze[x+1][y] != 0 && maze[x][y-1] != 0){
if(x >= 8 && y >= 8){
break;
}else{
maze[x][y] = 3;
y = pathStack.pop();
x = pathStack.pop();
}
y = pathStack.topValue();
int temp = pathStack.pop();
x = pathStack.topValue();
pathStack.push(temp);
}
}
}
void MazeSolveMethod::printPath() const{
cout<<"printPath"<<endl;
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
if(maze[i][j] == 2)
cout<<'*'<<" ";
else if(maze[i][j] == 3)
cout<<0<<" ";
else
cout<<1<<" ";
}
cout<<endl;
}
}