#include int starti = 1, startj = 1; //入口
int endi = 10, endj = 10; //出口
int success = 0; //成功
int maze[12][12] = {
//2表示有墙 0表示道路畅通
{2,2,2,2,2,2,2,2,2,2,2,2},
{2,0,0,0,0,0,0,0,0,0,2,2},
{2,0,2,2,2,0,2,0,0,2,0,2},
{2,0,0,0,2,0,2,0,0,2,0,2},
{2,0,2,0,2,0,2,0,0,2,0,2},
{2,0,0,0,0,0,2,0,2,2,0,2},
{2,0,2,2,2,2,2,0,0,0,0,2},
{2,0,2,2,2,2,2,2,2,0,0,2},
{2,0,2,2,2,0,0,0,0,0,0,2},
{2,0,2,2,2,0,2,2,2,2,0,2},
{2,0,0,0,0,0,0,0,0,0,0,2},
{2,2,2,2,2,2,2,2,2,2,2,2}
};
int main(int argc , char **argv)
{
int i,j;
printf("\n迷宫显示:\n");
for(i = 0; i < 12; i++)
{
for(j = 0; j < 12; j++)
//{
if(maze[i][j] == 2)
printf("|");
else
printf(" ");
//}
printf("\n");
}
printf("\n\n给小老鼠10秒钟的思考时间:\n\n");
sleep(5);
if(visit(starti,startj) == 0)
{
printf("没有找到出口\n");
}
else
{
printf("\n路径选择\n");
for(i = 0; i < 12; i++)
{
for(j = 0; j < 12; j++)
{
if(maze[i][j] == 2)
printf("|");
else if (maze[i][j] == 1)
printf("*");
//*表示小老鼠
else
printf(" ");
}
printf("\n");
}
}
return 0;
}
//程序的核心算法体现在这里,利用递归算法,由于我是设置的从坐标(1,1) 至(10,10),所以算法这里先进行j+1 i+1 在进行i-1 j-1;
int visit(int i, int j)
{
maze[i][j] = 1;
if(i == endi && j == endj)
{
success = 1;
}
if(success != 1 && maze[i][j+1] == 0)
visit(i,j + 1);
if(success != 1 && maze[i + 1][j] == 0)
visit(i + 1,j);
if(success != 1 && maze[i - 1][j] == 0)
visit(i - 1,j);
if(success != 1 && maze[i][j - 1] == 0)
visit(i,j - 1);
if(success != 1)
maze[i][j] == 0;
return success;
}