简单的实现了迷宫(深搜 并非是最短路径)。
我们规定’1’为墙,’0’为通路。为了避免越界,在迷宫外面加了一堵墙。当然也可以不需要墙。
实现很简单,用一个数组栈保存已访问过的位置,用四个if语句判断东南西北四个方向能否走通。
若往前已无路可走便退回上一个位置。
具体实现如下:
#include<stdio.h>
#include<stdlib.h>
#define N 6
int Table[N][N]=
{
1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 1, 1,
1, 0, 1, 1, 1, 1,
1, 0, 1, 0, 0, 1,
1, 0, 0, 0, 1, 1,
1, 1, 1, 1, 1, 1,
};
char *DefinDirection[4] = { "东", "南", "西", "北" };
int Stack[N*N] = { 0x00 };
void PrintTable(int T[][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf("%4d ", T[i][j]);
}
printf("\n");
}
}
void PrintRoute(int T[][N])
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 4; j++)
{
if (Stack[i] && Stack[i] == j + 1)
printf("%s ", DefinDirection[j]);
}
}
}
// 迷宫入口 1,1 出口 3,4
int FindWay(int T[][N])
{
int x, y, count,i = 0;
x = 1, y = 1;
while (1)
{
count = 0;
if (x == 1 && y == 1)
T[x][y] = 2;
if (x == 3 && y == 4)
{
return 1;
}
if (!T[x][y + 1])
{
T[x][y + 1] = 2;
y++;
Stack[i++] = 1; // 东
count++;
}
else if (!T[x + 1][y])
{
T[x + 1][y] = 2;
x++;
Stack[i++] = 2; // 西
count++;
}
else if (!T[x][y - 1])
{
T[x][y - 1] = 2;
y--;
Stack[i++] = 3; // 南
count++;
}
else if (!T[x - 1][y])
{
T[x - 1][y] = 2;
x--;
Stack[i++] = 4; // 北
count++;
}
if (i <= 0)
{
break;
}
if (!count)
{
int Direction = Stack[--i];
switch (Direction)
{
case 1:
y--;
break;
case 2:
x--;
break;
case 3:
x++;
break;
case 4:
y++;
break;
default:
break;
}
}
}
return 0;
}
int main()
{
if (FindWay(Table))
{
printf("哈哈我出来了!\n");
PrintTable(Table);
printf("路径是:");
PrintRoute(Table);
}
else
{
printf("找不到路啦%>_<%\n");
}
printf("\n\n");
system("pause");
return 0;
}