栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

用队列实现迷宫问题(C语言,数据结构)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用队列实现迷宫问题(C语言,数据结构)

问题描述

 给定一个M*N的迷宫,求一条从指定入口到出口的迷宫路径。用栈采用顺序栈存储结构。代码如下 

数据结构

用队列解决求迷宫路径问题。使用一个顺序队qu保存走过的方块。这里使用顺序队列而不是环形队列屎因为在找到出口时需要利用队列中的所有方块查找一条迷宫路径。 

运算算法

首先将入口(xi,yi),进队,在队列不空时循环出队一个方块e.然后查找方块e的所有相邻可走方块。当找到出口时,通过出口方块的pre值前推找到出口,所有经过的中间方块构成一条迷宫路径。利用的是广度优先搜索方法。为了正确输出路径,在前面的回推过程中修改路径上的每一个pre值,使该迷宫路径上的所有方块的pre值置为-1,然后从开头输出pre为-1的方块,从而正向输出了一条迷宫路径。 

代码实现 
#include
#include
#define MaxSize 50
#define M 8
#define N 8
typedef struct
{
	int i,j;
	int pre;
}Box;
typedef struct
{
	Box data[MaxSize];
	int front,rear;
}QuType;
void InitQueue(QuType*&q)
{
	q = (QuType*)malloc(sizeof(QuType));
	q->front = q->rear = -1;
}
void DestroyQueue(QuType*&q)
{
	free(q);

}
bool QueueEmpty(QuType*q)
{
	return(q->front == q->rear);
}
bool enQueue(QuType*&q, Box e)
{
	if (q->rear == MaxSize - 1)
		return false;
	q->rear++;
	q->data[q->rear] = e;
	return true;
}
bool deQueue(QuType*&q, Box&e)
{
	if (q->front == q->rear)
		return false;
	q->front++;
	e = q->data[q->front];
	return true;
}
 
int mg[M+2][N+2] = { {1,1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,0,1,0,1},
			         {1,0,0,1,0,0,0,1,0,1},{1,0,0,0,0,1,1,0,0,1},
			         {1,0,1,1,1,0,0,0,0,1},{1,0,0,0,1,0,0,0,0,1},
			         {1,0,1,0,0,0,1,0,0,1},{1,0,1,1,1,0,1,1,0,1},
			         {1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1} };
void print(QuType *qu, int front)
{

	int k = front, j, ns = 0;
	printf("n");
	do
	{
		j = k;
		k = qu->data[k].pre;
		qu->data[j].pre = -1;
	} while (k != 0);
	printf("一条迷宫路径如下:n");
	k = 0;
	while (k < MaxSize)
	{
		if (qu->data[k].pre == -1)
		{
			ns++;
			printf("t(%d,%d)", qu->data[k].i, qu->data[k].j);
			if (ns % 5 == 0)
				printf("n");
		}
		k++;
	}
		printf("n");

}
bool mgpath1(int xi, int yi, int xe, int ye)
{
	Box e;
	int i, j, di, il, jl;
	QuType*qu;
	InitQueue(qu);
	e.i = xi;e.j = yi;e.pre = -1;
	enQueue(qu, e);
	mg[xi][yi] = -1;
	while (!QueueEmpty(qu))
	{
		deQueue(qu, e);
		i = e.i;   j = e.j;
		if (i == xe && j == ye)
		{
			print( qu, qu->front);
			DestroyQueue(qu);
			return true;
		}


		for (di = 0;di < 4;di++)
		{
				switch (di)
			{
			case 0:
				il = i - 1;  jl = j;   break;
			case 1:
				il = i;   jl = j + 1; break;
			case 2:
				il = i + 1; jl = j;   break;
			case 3:
				il = i;   jl = j - 1; break;
			}
			if (mg[il][jl] == 0)
			{
				e.i = il;  e.j = jl;
				e.pre = qu->front;
				enQueue(qu, e);
				mg[il][jl] = -1;
			}
		}
	}
		DestroyQueue(qu);
		return false;
}

int main()
{
	if (! mgpath1(1, 1, M, N))
		printf("没有解");
	return 1;
}

 

结果 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847096.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号