华为面试题:迷宫问题 C语言源码
发布时间:2020-12-13 20:05:05 所属栏目:PHP教程 来源:网络整理
导读:定义1个2维数组N*M(其中2=N=10;2=M=10),如5 × 5数组下所示: int maze[5][5] = { 0,1, 0, }; 它表示1个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短线路。入口点为[0,0],既第1空是可
定义1个2维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示:
Input 1个N × M的2维数组,表示1个迷宫。数据保证有唯1解,不斟酌有多解的情况,即迷宫只有1条通道。 Output 左上角到右下角的最短路径,格式如样例所示。 5 5 #include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define MAX_PATH 256
int maze[10][10] = {0};
int route[100][2] = {0};
int main()
{
int row=0,line=0;
scanf("%d %d",&row,&line);
for (int i=0;i<row;i++)
{
for (int j=0;j<line;j++)
{
scanf("%d",&maze[i][j]);
}
}
//走迷宫
//堆栈:记录上1个位置
int xcurrent = 0;
int ycurrent = 0;
int count=0;
while(true)
{
if (maze[xcurrent+1][ycurrent]==0 && xcurrent+1<row)
{
//返回上1个位置
if (route[count⑴][0]==xcurrent+1 && route[count⑴][1]==ycurrent)
{
maze[xcurrent][ycurrent]=1;//设置为墙
count--;
xcurrent++;
}
else
{
route[count][0]=xcurrent;
route[count][1]=ycurrent;
count++;
xcurrent++;
}
}
else if (maze[xcurrent][ycurrent+1]==0 && ycurrent<line)
{
if (route[count⑴][0]==xcurrent && route[count⑴][1]==ycurrent+1)
{
maze[xcurrent][ycurrent]=1;//设置为墙
count--;
ycurrent++;
}
else
{
route[count][0]=xcurrent;
route[count][1]=ycurrent;
count++;
ycurrent++;
}
}
else if (maze[xcurrent⑴][ycurrent]==0 && xcurrent⑴>=0)
{
if (route[count⑴][0]==xcurrent⑴ && route[count⑴][1]==ycurrent)
{
maze[xcurrent][ycurrent]=1;//设置为墙
count--;
xcurrent--;
}
else
{
route[count][0]=xcurrent;
route[count][1]=ycurrent;
count++;
xcurrent--;
}
}
else if (maze[xcurrent][ycurrent⑴]==0 && ycurrent⑴>=0)
{
if (route[count⑴][0]==xcurrent && route[count⑴][1]==ycurrent⑴)
{
maze[xcurrent][ycurrent]=1;//设置为墙
count--;
ycurrent--;
}
else
{
route[count][0]=xcurrent;
route[count][1]=ycurrent;
count++;
ycurrent--;
}
}
if (xcurrent==row⑴ && ycurrent==line⑴)
{
route[count][0]=xcurrent;
route[count][1]=ycurrent;
count++;
break;
}
}
for (int i=0;i<count;i++)
{
printf("(%d,%d)
",route[i][0],route[i][1]);
}
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |