#include "pch.h"
#include <iostream>
using namespace std;
#define M 8
#define N 8
int a[M+2][N+2] =
{
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,0,1,1},
{1,0,1,0,0,1,1,1,1,1},
{1,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,1,1,0,0,1},
{1,1,1,1,0,0,0,0,1,1},
{1,0,0,0,1,0,1,1,0,1},
{1,0,1,0,1,0,1,1,1,1},
{1,0,0,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
struct
{
int i;
int j;
int direction;
}Stack[100],Path[100][200];
int top = -1;
int roadnumber = 1;
int minlength = 100;
int minroadnumber=1;
static void one_path()
{
int k;
cout <<"第"<< roadnumber++<<"条路:"<< endl;
for (k = 0; k <= top; k++)
{
cout << "(" << Stack[k].i << "," << Stack[k].j << ")";
if (k != top) cout << "->";
}
cout << endl;
if (top + 1 <=minlength)
{
Path[minroadnumber][0].i= top + 1;
for (k = 1; k <= top+1; k++)
{
Path[minroadnumber][k].i = Stack[k-1].i;
Path[minroadnumber][k].j = Stack[k-1].j;
Path[minroadnumber][k].direction = Stack[k-1].direction;
}
minroadnumber++;
minlength = top + 1;
}
}
static void min_path()
{
cout << "最短路径长度为:" << minlength << endl;
cout << "路径为:"<< endl;
for (int k = 1; k <=minroadnumber; k++)
{
if (Path[k][0].i == minlength)
{
for (int l = 1; l <=minlength; l++)
{
cout << "(" << Path[k][l].i << "," << Path[k][l].j << ")";
if (l != minlength) cout << "->";
}
cout << endl;
}
}
cout << endl;
}
static void all_path(int xi, int yi, int xe, int ye)
{
int i, j, di,X, Y;
int flag = 0;
top++;
Stack[top].i = xi;
Stack[top].j = yi;
Stack[top].direction = 0;
a[xi][yi] = -1;
int f=0;
while (top > -1)
{
i = Stack[top].i;
j = Stack[top].j;
di = Stack[top].direction;
if (i == xe && j == ye)
{
one_path();
f = 1;
a[i][j] = 0;
top--;
i = Stack[top].i;
j = Stack[top].j;
di = Stack[top].direction;
}
flag = 0;
while (di < 4 && flag==0)
{
di++;
switch (di)
{
case 1:X = i - 1;Y = j;break;
case 2:X = i;Y = j + 1;break;
case 3:X = i + 1;Y = j;break;
case 4:X = i;Y = j - 1;break;
}
if (a[X][Y] == 0)
flag=1;
}
if (flag)
{
Stack[top].direction = di;
top++;
Stack[top].i = X; Stack[top].j = Y; Stack[top].direction = 0;
a[X][Y] = -1;
}
else
{
a[i][j] = 0;
top--;
}
}
if (f == 0) cout << "无路可走!" << endl;
else
{
cout << "一共有" << roadnumber - 1 << "条路!" << endl;
min_path();
}
}
int main(int argc, char *argv[])
{
cout << "迷宫如下图所示:(1表示墙0表示通路)" << endl;
for (int i = 0; i < M + 2; i++)
{
for (int j = 0; j < N + 2; j++)
cout << a[i][j] << '\t';
cout << endl;
}
cout << "所有路径如下:" << endl;
all_path(1, 1, M, N);
return 0;
}
