迷宫问题,上下左右四个方向可走,为
{ { 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 0, 0 },
{ 0, 1, 0, 1, 1, 0 },
{ 0, 1, 1, 1, 0, 0 },
{ 0, 0, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 0 } };
0不可走,1可走
#include<iostream>
using namespace std;
#define N 10
struct Direction
{
int x, y;
int d;
};
struct
{
int m, n;
}offset[4] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; //按照可能取值取数组大小,本题路径四个方向
int b[6][6] = { { 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0, 0 }, { 0, 1, 0, 1, 1, 0 },
{ 0, 1, 1, 1, 0, 0 }, { 0, 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0 } };
class MGPath
{
Direction Stack[50];
Direction PathWay[50]; //自行定义大小为MaxSize,小心越界
int mg[N][N];
int d;
int top;
int length;
public:
MGPath();
MGPath(int a[N][N]); //应注意在a[][]中入口出口的确定,即入口出口的初始坐标
//可增加函数来确定void begend(int x1,int x2,int y1,int y2)
//此处省略按照题目默认的来
~MGPath(){}
void Push(int x, int y, int d);
void mgpath();
};
MGPath::MGPath() //默认迷宫按照本题指定赋值
{
top = -1;
d = 0;
length = 50;
int i, j;
for (i = 0; i < 6; i++)
for (j = 0; j < 6; j++)
mg[i][j] = b[i][j];
}
/*MGPath::MGPath(int a[N][N]) //此处自己设定迷宫,若用自己设定的迷宫则需自己指定出口入口
{
top = -1;
d = 0;
length = 50;
int i, j;
for (i = 0; i < 10;i++)
for (j = 0; j < 10; j++)
mg[i][j] = a[i][j];
}*/
void MGPath::Push(int x, int y, int d) //迷宫坐标入栈
{
top++;
Stack[top].x = x;
Stack[top].y = y;
Stack[top].d = d;
mg[x][y] = 0;
}
void MGPath::mgpath()
{
int a, b, g, h, di;
int i;
int find;
Push(1, 1, 0); //a,b初始坐标,di初始方向
while (top > -1)
{
a = Stack[top].x;
b = Stack[top].y;
di = Stack[top].d; ///////////////////
if (a == 4 && b == 4)
{
for (i = 0; i <= top; i++)
cout << '(' << Stack[i].x << ',' << Stack[i].y << ')' << endl;
cout << endl;
if (top + 1 < length)
{
for (i = 0; i <= top; i++)
PathWay[i] = Stack[i];
length = top + 1;
}
mg[a][b] = 1;
top--;
a = Stack[top].x;
b = Stack[top].y;
di = Stack[top].d + 1;
}
find = 0;
while (di <= 3&&(find==0))
{
g = a + offset[di].m;
h = b + offset[di].n;
if (mg[g][h] == 1)
find = 1;
else
di++;
}
if (!(find))
{
top--;
mg[a][b] = 1;
}
else
{
Stack[top].d = di;
Push(g, h, 0);
}
}
for (i = 0; i < length;i++)
cout << '(' << PathWay[i].x << ',' << PathWay[i].y << ')' << endl;
}
void main()
{
MGPath Mp;
Mp.mgpath();
}
default中没有采用break