#include<stdio.h>
#include<stdlib.h>
/*数组里面去寻路:位置-->通过行和列去寻找*/
struct position
{
int row;/*记录第几行第几列*/
int cols;
};
/*我们需要一个栈,去存储路径,栈的容器就是一个结构体数组*/
struct position pathStack[100];/*栈内存存放路径*/
int stackTop = -1;/*栈顶标记*/
int **maze = NULL;/*可以用二维指针去描述二维数组,用二维数组描述地图*/
int size = 0;/*迷宫的大小*/
int **makeArray(int row, int cols)
{
int **array = (int**)malloc(sizeof(int *)*row);/*定义一个临时变量,存放多个一级指针*/
/*然后用for循环为每一个一级指针申请一块内存,存放多个整形数据,然后就是二维数组*/
for(int i = 0;i<cols;i++)
{
array[i] = (int*)malloc(sizeof(int)*cols);
}
return arraay;
}
/*用户输入一个迷宫*/
void createNaze()
{
print("输入迷宫大小\n");
scanf("%d", &size);
maze = makeArray(size+2, size+2);/*这个表示边框*/
printf("输入迷宫");
for(int i =1;i <=size;i++)
{
for(int j = 1; j <= size; j++)
{
scanf("%d",&maze[i][j]);
}
/*加边框:1 表示不可以走*/
for(int i = 0; i <= size + 1;i++)
{
maze[0][i] = maze[size + 1][i] = 1;/*上下两行*/
maze[i][0] = maze[i][size + 1] = 1; /*左右两列*/
}
}
}
//找路径
int findPath()
{
/* //偏移属性描述出来
struct position offset[4] ;*0-3表示四个方向*/
//往右边走
offset[0].row = 0;
offset[0].cols = 1;
//往下边走
offset[1].row = 1;
offset[2].cols = 0;
//往左走
offset[2].row = 0;
offset[2].cols = -1;
//往上走
offset[3].row = -1;
offset[3].cols = 0;
*/
/*等效于*/
struct position offset[4] = {{0,1},{1,0},{0,-1},{-1,0}};
/*选定路口*/
struct position here ={1,1}; /*当前移动的位置*/
/*走迷宫:记录走过的路径*/
maze[1][1] = 1;;
/*走过的地方都标记为1*/
int option = 0; //下一个移动方向
int endOption = 3; //终止方向
while (here.row!=size||here.rols != size)/*终点位置是size,不等于终点位置就一直往下去找*/
{
/*相邻的位置做移动*/
int rowNum,colsNum; //记录下标变化
while(option <= endOption)
{
/*行列的变化=原位置+偏移值,且偏移值由方向决定*/
rowNum=here.row+offset/*竖直行记录下来。当前行row加上偏移量offset[option].row*/
/*同理,对列*/
colsNum = here.cols + offset[option].cols;
/*一但确定一个方向可以走,就需要去下一步*/
if(maze[rowNum][colsNum] == 0)
break; /*退出循环走一遍,在这里才是 1 表示不可走*/
/*不能走换位置测试*/
option++;
}
/*可以移动*/
if(option <= endOption)
{
/*走到下一个*/
pathStack[++stackTop] = here;
/*走过,要改变当前位置*/
here.row = rowNum;
here.cols = colsNum;
/*走过的路径给堵上*/
maze[rowNum][colsNum] = 1;
option =0;/*把起始方向置为0,去找下一个位置*/
}
else //option = 4;表示没有可以走的地方
{
/*回到上一步去*/
if(stackTop == -1)
return 0; /*表示无路可走,即没有路径*/
/*通过出栈的方式回到上一步*/
struct postion next = pathStack[stackTop];
stackTop--;
/*方向的处理*/
if(next.row == here.row) /*行没变,左右走*/
{
option = 2+next.cols-here.cols;
}
else
{
option = 3 + next.row -her.cols;
}
here = next; /*位置回退到上一步*/
}
}
return 1;
}
/*打印路径*/
void printPath
{
printf("路径方式:\n");
struct position curPos;
while(stackTop != -1)
{
curPos == pathStack[stackTop];/*栈的终点位置,就是栈顶*/
/*curPos为当前位置*/
stackTop--;
printf("(%d,%d)-->",curPos.row, curPos.cols);
}
printf("\n");
}
int main()
{
createMaze();
if(findpath)
{
printPath();
}
else
{
printf("没有路径可走");
}
system("pause");
return 0;
}