0
点赞
收藏
分享

微信扫一扫

迷宫寻路问题简单思路(c语言)

凯约 2022-04-07 阅读 89
c语言c++

核心思想:

step1:设临时变量location存放当前迷宫出口

step2:依次判断location的四个方向(上,右,下,左)是否可行。

step3:如果方向可行,将location压入堆栈,然后更新位置(前进一步)。如果四个方向都不可行,弹出堆栈的栈顶元素,更新位置(后退一步)。

step4:循环step2,step3步骤,直到栈空或者找到入口,然后进行step5。

step5:如果栈空,代表无法找到出口,输出无解。如果找到入口,该堆栈的元素为迷宫的出口路径的每一个位置,输出路径。

代码:

1.定义相关变量和函数。

#include<stdio.h>
#include<stdlib.h>
#define Maxlength 100
//Location表示了位置的信息,Direction表示该位置尝试前进的方向
//Direction(1,2,3,4)分别代表(上,右,下,左)
struct Location{
	short int Row;
	short int Col;
	short int Direction;
};
//移动的坐标
struct Move{
	short int Row;
	short int Col;
};
//存放Location类位置的堆栈
struct Path{
	struct Location *path[Maxlength];
	int top;
};
//以下为堆栈基本操作
void push(struct Path *paths,struct Location *location)
{
	paths->top++;
	paths->path[paths->top]=location;
}
void pop(struct Path *paths)
{
	paths->top--;
}
//输出迷宫
void printMap(int map[][11])
{
	int i,j;
	for(i=0;i<11;i++)
		{
			for(j=0;j<11;j++)
			printf("%d ",map[i][j]);
			printf("\n");
		}
}

2.初始化

int main(){
	int map[11][11]={
	{0,0,0,0,0,0,0,0,0,0,0},
	{0,1,1,1,1,1,1,1,1,1,0},
	{0,0,0,1,0,1,0,0,0,0,0},
	{0,0,1,1,0,1,0,0,0,0,0},
	{0,0,1,0,0,0,0,0,0,0,0},
	{0,0,1,1,0,0,0,0,0,0,0},
	{0,0,0,1,1,0,0,0,0,0,0},
	{0,0,0,1,0,0,0,0,0,0,0},
	{0,0,0,1,1,1,1,1,1,1,0},
	{0,0,0,0,0,0,0,0,0,1,0},
	{0,0,0,0,0,0,0,0,0,0,0},
	};
	//标记已经走过的位置,防止位置在尝试方向的时候,把走过的位置当成新的位置。
    int mask[11][11]={0};
    //初始化出口和入口的位置信息
	struct Location *In = malloc(sizeof(struct Location));In->Col=1;In->Row=1;
	struct Location *Out = malloc(sizeof(struct Location));Out->Col=9;Out->Row=9;
	//先将出口信息赋给location
    struct Location *location = Out;location->Direction=1;mask[Out->Row][Out->Col]=1;
	//初始化paths堆栈,将出口压入堆栈。
    struct Path *paths = malloc(sizeof(struct Path));paths->top=-1;push(paths,Out);
	//依次代表四个方向的坐标变化,move[0]无意义。
    struct Move move[5]={{0,0},{-1,0},{0,1},{1,0},{0,-1}};

3.路径的寻找。

while(!(location->Row==In->Row&&location->Col==In->Col)&&!(paths->top==-1))
	{
	    //记录按方向前进后的坐标
		int Row=move[location->Direction].Row+location->Row;
		int Col=move[location->Direction].Col+location->Col;
      
		if(map[Row][Col]==1&&mask[Row][Col]==0)
		{    
            //该位置为1(不是墙),mask=0(没有走过)
            //更新location的信息,并标记该位置已经走过
			location = malloc(sizeof(struct Location));
			push(paths,location);
			location->Row=Row;
			location->Col=Col;
			location->Direction=1;
			mask[Row][Col]=1;
		}
		else if(location->Direction==4)
		{
			//代表四个位置都不可行
            pop(paths);
			if(paths->top>=0)
			location = paths->path[paths->top];
		}
		else location->Direction++;
	}

4.输出迷宫。

if(paths->top==-1)
	printf("无解");
	else
	{
		//输出
		for(;paths->top!=-1;paths->top--)
		{
			map[paths->path[paths->top]->Row][paths->path[paths->top]->Col]=8;
		}
		printMap(map);
	}
}

终:复制以上代码即可运行程序。

举报

相关推荐

0 条评论