以下程序打印出老鼠走迷宫全部的路径:
#include<stdio.h>
#define LEN 9
int maze[9][9] = {
{2, 0, 2, 2, 2, 0, 2, 2, 2},
{2, 0, 2, 2, 2, 0, 0, 2, 2},
{2, 0, 0, 0, 0, 0, 0, 0, 2},
{2, 0, 2, 2, 0, 2, 2, 0, 2},
{2, 0, 0, 2, 0, 2, 2, 0, 2},
{2, 0, 0, 2, 0, 2, 2, 0, 2},
{2, 0, 0, 2, 0, 0, 0, 0, 0},
{2, 0, 0, 0, 0, 2, 2, 2, 2},
{2, 0, 2, 2, 0, 2, 2, 2, 2},
}; //构建迷宫
int start_x = 1, start_y = 0; //设置起点
int end_x = 8, end_y = 4; //设置终点
void step(int x, int y);
void print_maze();
int main(int argc, char argv[])
{
printf("maze:\n"); //打印迷宫图,为方便查看,将数字换为图形打印
print_maze();
step(start_x, start_y);
return 0;
}
void step(int x, int y) //用递归算法求解路径
{
maze[x][y] = 1;
if(x == end_x && y == end_y)
{
print_maze(); //打印函数放入递归中,每找到一条成功路径打印一次
}
if(y < (LEN - 1) && maze[x][y + 1] == 0){step(x, y + 1);} //边界条件,避免溢出,感谢 @别把白天当黑夜 指正
if(x < (LEN - 1) && maze[x + 1][y] == 0){step(x + 1, y);}
if(y > 0 && maze[x][y - 1] == 0){step(x, y - 1);}
if(x > 0 && maze[x - 1][y] == 0){step(x - 1, y);}
maze[x][y] = 0;
}
void print_maze()
{
int x, y;
for(x = 0; x < LEN; x++)
{
for(y = 0; y < LEN; y++)
{
if(maze[x][y] == 2)
printf("2");
else if(maze[x][y] == 1)
printf("1");
else if(maze[x][y] == 0)
printf("0");
}
printf("\n");
}
printf("\n");
}