🐻作者: 芝士小熊饼干
📖 系列专栏: 数据结构->迷宫问题
🎉 支持我: 点赞 👍 +收藏 ⭐ +留言 📝
问题描述:
迷宫可以以二维数组来存储表示。0表示通路,1表示障碍。注意这里规定移动可以从上、下、左、右四方方向移动。坐标以行和列表示,均从0开始,给定起点(0,0)和终点(4,4),迷宫表示如下:
int maze[5][5]={
{0,0,0,0,0},
{0,1,0,1,0},
{0,1,1,0,0},
{0,1,1,0,1},
{0,0,0,0,0}
};
代码实现:
#include<stdio.h>
#include<stdlib.h>
#include<bool.h>
typedef struct postion
{
int row;
int col;
}PT;
void PrintMaze(int **maze,int N,int M)
{
for(int i=0;i<N;++i)
{
for(int j=0;j<M;++j)
{
printf("%d ",maze[i][j]);
}
printf("\n");
}
printf("\n");
}
//
bool IsPass(int**maze,int N,int M,PT pos)
{
if( pos.row>=0 && pos.row<N
&&pos.col>=0 && pos.col < M
&& maze[pos.row][pos.col]==0)
{
return true;
}
else
{
return false;
}
}
//
bool GetMazePath(int**maze,int N,int M,PT cur)
{
if(cur.row=N-1 && cur.col == M-1)
{
return true;
}
// 探测cur位置的上下左右四个方向
PT next;
maze[cur.row][cur.col]=2;
// 上
next=cur;
next.row-=1;
if(IsPass(maze,N,M,next))
{
if(GetMazePath(maze,N,M,next))
return true;
}
// 下
next=cur;
next.cor-=1;
if(IsPass(maze,N,M,next))
{
if(GetMazePath(maze,N,M,next))
return true;
}
//左
next=cur;
next.row+=1;
if(IsPass(maze,N,M,next))
{
if(GetMazePath(maze,N,M,next))
return true;
}
// 右
next=cur;
next.cor+=1;
if(IsPass(maze,N,M,next))
{
if(GetMazePath(maze,N,M,next))
return true;
}
return false;
}
int main()
{
int N=0,M=0;
while(scanf("%d %d",&N,&M)!=EOF)
{// int a[n][m];
// 不支持,动态开辟
// 动态开辟二维数组
int** maze =(int**)malloc(sizeof(int*)*N);
for(int i=0;i<N;++i)
{
maze[i]=(int*)malloc(sizeof(int)*M);
}
// 二维数组的输入
for(int i=0;i<N;++i)
{
for(int j=0;j<M;++j)
{
scanf("%d",&maze[i][j]);
}
}
// 输出
// PrintMaze(maze,N,M);
PT entry={0,0};
if(GetMazePath(maze,N,M,entry))
{
printf("找到通路\n")
}
else
{
printf("没有找到通路\n")
}
//动态二维数组的释放
for(int i=0;i<N;++i)
{
free(maze[i]);
}
free(maze);
maze=NULL;
}
return 0;
}