~小游戏开发——迷宫(递归版)~

前面我们写到迷宫的普通版,那这篇文章就来写一下如何用递归来实现!

递归实现迷宫问题同普通版差不多,其中关键思路、初始化及打印地图、创建位置结点类等与普通版一样,只有判断坐标的合理性与寻找迷宫通路的方法不同而已。

源代码如下:

#include <iostream>
#include <assert.h>
using namespace std;

#include <stack>
#pragma warning(disable:4996)

const size_t N = 10;

void InitMaze(int maze[][N], size_t N)  //初始化迷宫图
{
	FILE* fout = fopen("Maze.txt","r");
	assert(fout);

	for(size_t i=0; i<N; ++i)
	{
		for(size_t j=0; j<N; )
		{
			//获得迷宫图上坐标的ASCII值
			char ch = fgetc(fout);

			if((ch == '0') || (ch == '1'))
			{
				maze[i][j] = ch - '0';
				++j;
			}
		}
	}
}

void PrintMaze(int maze[][N], size_t N)  //打印迷宫图
{
	for(size_t i=0; i<N; ++i)
	{
		for(size_t j=0; j<N; ++j)
		{
			cout<<maze[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
}

struct Pos  //定义位置结点
{
	size_t _row;  //行
	size_t _col;  //列
};

bool CheckAccess(int maze[][N], size_t N, Pos pos)  //判断坐标的位置是否合理
{
	if(((pos._row>=0) && (pos._row<N)) 
		&& ((pos._col>=0) && (pos._col<N)) 
		&& (maze[pos._row][pos._col] == 0))
	{
		return true;
	}

	return false;
}

//运用递归
bool GetMazePathR(int maze[][N], size_t N, Pos cur)
{
	maze[cur._row][cur._col] = 2;  //将已走过的位置赋值为2

	Pos next;

	//上
	next = cur;
	next._row--;

	if(CheckAccess(maze, N, next))
	{
		if(GetMazePathR(maze, N, next))
		{
			return true;
		}
	}

	//右
	next = cur;
	next._col++;
	
	if(CheckAccess(maze, N, next))
	{
		if(GetMazePathR(maze, N, next))
		{
			return true;
		}
	}

	//下
	next = cur;
	next._row++;

	if(CheckAccess(maze, N, next))
	{
		if(GetMazePathR(maze, N, next))
		{
			return true;
		}
	}
	
	//左
	next = cur;
	next._col--;

	if(CheckAccess(maze, N, next))
	{
		if(GetMazePathR(maze, N, next))
		{
			return true;
		}
	}

	return false;
}

void TestMaze()
{
	int maze[N][N];

	InitMaze(maze, N);
	PrintMaze(maze, N);

	Pos entry;
	entry._row = 2;
	entry._col = 0;

	GetMazePathR(maze, N, entry);

	PrintMaze(maze, N);
}

int main()
{
	TestMaze();

	system("pause");
	return 0;
}

 

我们打印迷宫地图时,采用了文件的方式,如果有志同道合的人看到了这篇文章,想要动手操作一下的话,需要编写一份文本文件Maze.txt,并将它加载到项目的文件夹中。

下图为样例。

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值