//
// stack.h
//
#ifndef stack_h
#define stack_h
static const int Size = 50;
struct point
{
public:
int x;
int y;
int dir;
};
struct stack
{
private:
public:
point data[Size];
int top;
void init()
{
top = 0;
}
bool is_empty()
{
return top == 0;
}
bool pop(point & e)
{
if(top == 0)
return false;
else
{
e = data[top-1];
top--;
return true;
}
}
bool push(point e)
{
if(top >= Size)
return false;
else
{
top++;
data[top-1] = e;
return true;
}
}
point top_elem()
{
return data[top-1];
}
};
#endif /* stack_h */
//main.cpp
#include <iostream>
#include "stack.h"
const int M = 8, N = 8;
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 mgpath(int x1, int y1, int m, int n);
int main()
{
if(!mgpath(1,1,M,N))
std::cout << "该迷宫问题没有解!" << std::endl;
return 0;
}
bool mgpath(int x1, int y1, int m, int n)
{
// 从(x1,y1)出发,顺时针搜索周围mg为0的点,有则进栈改该点mg为-1,记下pre
// 没有则将栈顶元素mg改回0并弹栈,直到到达终点
// 栈顶
//元素为终点则找到了路径,栈为空则没找到
stack st;
st.init();
point pt[M+2][N+2];
for(int row = 0; row < M + 2; row++)
{
for(int col = 0; col < N + 2; col++)
{
pt[row][col].x = row;
pt[row][col].y = col;
pt[row][col].dir = 0;
}
}
point p_temp;
pt[x1][y1].x = x1;
pt[x1][y1].y = y1;
st.push(pt[x1][y1]);
mg[x1][y1] = -1;
int x = x1,y = y1;
int x_next = x1, y_next = y1;
bool next;
while(!st.is_empty() && (st.top_elem().x != m || st.top_elem().y != n))
{
next = false;
while(pt[x][y].dir < 4)
{
switch(pt[x][y].dir)
{
case 0: x_next = x-1;
y_next = y;
break;
case 1: x_next = x;
y_next = y+1;
break;
case 2: x_next = x+1;
y_next = y;
break;
case 3: x_next = x;
y_next = y-1;
break;
}
if(!mg[x_next][y_next])
{
next = true;
break;
}
pt[x][y].dir = pt[x][y].dir+1;
}
if(next)
{
// pt[x_next][y_next].x = x_next;
// pt[x_next][y_next].y = y_next;
st.push(pt[x_next][y_next]);
mg[x_next][y_next] = -1;
x = x_next;
y = y_next;
}
else
{
mg[x][y] = 0;
st.pop(p_temp);
x = st.top_elem().x;
y = st.top_elem().y;
pt[x][y].dir = pt[x][y].dir + 1;
}
}
if(st.is_empty())
{
return false;
std::cout << "No way\n";
}
else if(st.top_elem().x == m && st.top_elem().y == n)
{
std::cout << "This way: ";
for(int i = 0; i < st.top; i++)
std::cout << "(" << st.data[i].x << ", " << st.data[i].y << ") ";
std::cout << std::endl;
return true;
}
}