#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
#define M 8
#define N 8
typedef struct//定义方块类型
{
int x;
int y;
int di;
}box;
int mg[M + 2][N + 2] =
{
{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}
};//定义一个迷宫
bool mglj(int xi, int yi, int xe, int ye)
{
box lj[100], e{}; int x, y, di, x1, y1, k; bool find;
stack<box>st;
e.x = xi; e.y = yi; e.di = -1;
st.push(e);
mg[xi][yi] = -1;
while (!st.empty())
{
x = st.top().x; y = st.top().y; di = st.top().di;
if (x== xe && y == ye)
{
cout << "迷宫路径如下" << endl;
k = 0;
while (!st.empty())
{
lj[k++] = st.top();
st.pop();
}
while (k >= 1)
{
k--;
cout << lj[k].x <<"," << lj[k].y << "," << lj[k].di<< endl;
if ((k + 2) % 5 == 0)
cout << "\n" << endl;
}
cout << "\n" << endl;
return true;
}
find = false;
while (di < 4 && !find)
{
di++;
switch (di)
{
case 0:x1 = x - 1; y1 = y; break;
case 1:x1 = x; y1 = y + 1; break;
case 2:x1 = x + 1; y1 = y; break;
case 3:x1 = x; y1 = y - 1; break;
}
if (mg[x1][y1] == 0)
find = true;
}
if (find)
{
st.pop();
e.di = di;
st.push(e);
e.x = x1; e.y = y1; e.di = -1;
st.push(e);
mg[x1][y1] = -1;
}
else
{
st.pop();
mg[e.x][e.y] = 0;
}
}
return false;
}
int main()
{
if (!mglj(1, 1, M, N))
cout << "该迷宫问题没有解!" << endl;
return 1;
}
为什么会把死胡同末端的方块显示出来?
我发现把这里修改一下就可以了
st.pop();
e.di = di;
st.push(e);
改成
st.top().di=di;
但是为什么呢,删除在添加和替换有什么区别?