#include<stdio.h>
#include<stdlib.h>
#define m 6
#define n 8
typedef struct
{
int x,y;
}items;//定义方向变量
int path(int maze[][n+2],items move[],int x,int y,int step)
{
int i;
step++;
maze[x][y]=step;
if(m==x&&n==y)
{
return 1;//起始位置是出口
}
for(i=0;i<4;i++)
{
if(maze[x+move[i].x][y+move[i].y]==0)
if(path(maze,move,x+move[i].x,y+move[i].y,step))
return 1;//如果下一个是出口,返回
}
step--;
maze[x][y]=0;//无路径
}
int main()
{
items move[4];
move[0].x=0;
move[0].y=1;
move[1].x=1;
move[1].y=0;
move[2].x=0;
move[2].y=-1;
move[3].x=-1;
move[3].y=0;
int migong[m+2][n+2]={
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,0,1,1,0,1},
{1,0,0,0,1,1,1,1,0,1},
{1,0,0,0,0,0,1,1,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
if(path(migong,move,1,1,1))
{
for(int i=0;i<m+2;i++)
{
for(int j=0;j<n+2;j++)
printf("%d ",migong[i][j]); //打印迷宫
printf("\n");
}
}
return 0;
}
迷宫问题递归解
最新推荐文章于 2024-03-01 20:53:10 发布