数据结构 迷宫的非递归实现(回溯法)

迷宫的非递归实现(回溯法)

       首先在项目工程所在文件夹下放入存有迷宫数据的文件Maze.txt,通过fopen("Maze.txt","r")读取文件中的数据,并进行转化。也可以在代码中直接定义一个二维数组来构建迷宫。

        我们采用回溯法来取得迷宫的通路,我们从给出的入口(entry)出开始根据上、下、左、右的方向试探,若有通路,则将当前位置压入栈中并做上标记(2)。若走入一个死角(除来路,其他路皆不通),则原路返回并做上标(3)。

数据结构 迷宫的非递归实现(回溯法)_第1张图片

代码实现如下:

#include
#include
#include
using namespace std;

#pragma warning (disable:4996)

const static size_t N = 10;

void Initmaze(int maze[][N], size_t n)//从文件中读取数据,初始化迷宫
{
	FILE *file = fopen("Maze.txt", "r");
	assert(file);

	for (size_t i = 0; i < n; i++)
	{
		for (size_t j = 0; j < n;)
		{
			char ch = fgetc(file);
			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 Access(int maze[][N], size_t n, Pos next)//判断位置是否合法及是否是通路
{
	if (next._row0 
		&& next._col0 
		&& maze[next._row][next._col] == 0)
	{
		return true;
	}
	return false;
}

bool GetMazePath(int maze[][N], size_t n,Pos entry)
{
	stack path;//建立一个栈用来存储通路
	path.push(entry);//将入口压入栈底
	while (!path.empty())
	{
		Pos cur = path.top();
		if (cur._row == n - 1)
		{
			return true;
		}

		Pos next = cur;
		maze[cur._row][cur._col] = 2;//将走过的路标记为2

		//上
		next = cur;
		next._row--;
		if (Access(maze, n, next))
		{
			path.push(next);
			continue;
		}

		//下
		next = cur;
		next._row++;
		if (Access(maze, n, next))
		{
			path.push(next);
			continue;
		}

		//左
		next = cur;
		next._col--;
		if (Access(maze, n, next))
		{
			path.push(next);
			continue;
		}

		//右
		next = cur;
		next._col++;
		if (Access(maze, n, next))
		{
			path.push(next);
			continue;
		}

		Pos top = path.top();
		maze[top._row][top._col] = 3;//重复走过的路标记为3
		path.pop();
	}
	return false;
}


int main()
{
	int maze[N][N];
	Pos entry;
	entry._row = 3;
	entry._col = 0;

	Initmaze(maze, N);
	Printmaze(maze, N);

	GetMazePath(maze, N, entry);
	Printmaze(maze, N);

	system("pause");
	return 0;
}


你可能感兴趣的:(数据结构(C++))