迷宫的试探与回溯,对应于压栈与出栈过程。
试探与回溯,深度遍历的过程,不保证输出的一条路径就是最短路径,广度遍历可以。
//
// main.cpp
// stack
//
// Created by scnulpc on 2018/10/11.
// Copyright © 2018年 scnulpc. All rights reserved.
//
#include <iostream>
#include <stack>
#define max 100
using namespace std;
//算法输出迷宫的一条路径
//map[][]迷宫的地图
//sign[][]迷宫的标志
int map[max][max];
int sign[max][max];
struct item
{
int x;
int y;
string step;
item(int a,int b,string c)
{
x=a;y=b;step = c;
}
};
struct offset
{
int a,b;
offset(int x,int y)
{
a=x;b=y;
}
};
offset* Move[8]={new offset(-1,0),new offset(-1,1),new offset(0,1),new offset(1,1),new offset(1,0),new offset(1,-1),new offset(0,-1),new offset(-1,-1)};
void path(int row,int column)
{
stack<item*> s ;item* current;item* forhead;
int i,j,g,h;//(i,j)当前坐标,(g,h) 下一步坐标
item *start = new item(1,1,"(1,1)->");
s.push(start);
sign[1][1]=1;
while (!s.empty())
{
current = s.top();
forhead = current;
s.pop();
i=current->x;
j=current->y;
int d=0;
while (d<8)
{
g=i+Move[d]->a;
h=j+Move[d]->b;
if (g==row&&h==column)
{
cout<<forhead->step+"(";
cout<<g;
cout<<",";
cout<<h;
cout<<")"<<endl;
return ;
}
else if (map[g][h]==0&&sign[g][h]==0)
{
sign[g][h]=1;
i=g;
j=h;
d=0;
forhead = new item(g,h,forhead->step+"("+to_string(i)+","+to_string(j)+")"+"->");
s.push(forhead);
}
else d++;
}
}
cout<<"no way"<<endl;
}
void init()
{
memset(map, 1, sizeof(map));
memset(sign, 0, sizeof(sign));
}
int main(int argc, const char * argv[])
{
init();
int n,m;
cout<<"输入地图n行 m列"<<endl;
cin>>n>>m;
for (int i=1; i<=n; i++)
{
for (int j=1; j<=m; j++)
{
cin>>map[i][j];
}
}
path(5, 4);
return 0;
}