数据结构——迷宫问题

迷宫问题的总体思路是,从迷宫的入口出发,沿着某一个方向向前试探,若能够行得通,则继续往前走,否则原来返回,再换另一个方向继续试探,直到所有可能的通路都被试探过,为了保证在任何一个位置都能够原来返回,需要设置一个堆栈结构来保存从入口到当前位置的路径。

“Maze.h”

<span style="font-size:18px;"><strong>#pragma once

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

void InitMaze(int* maze,size_t n)
{
	assert(maze);
	FILE* fout = fopen("MazeMap.txt","r");

	for (int i = 0;i < n;i++)
	{
		for (int j = 0;j < n;)
		{
			char c = fgetc(fout);
			if (c == '0' || c == '1')
			{
				maze[i * n + j] = c - '0';
				j++;
			}
		}
	}
	fclose(fout);
}

void PrintMaze(int* maze,size_t n)
{
	assert(maze);

	for (int i = 0; i < n;i++)
	{
		for (int j = 0;j < n;j++)
		{
			cout<<maze[i * n +j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
}

struct Pos
{
	int _row;//行
	int _col;//列
};

bool CheckIsAccess(int* maze,size_t n,Pos entry)//数组边界条件的检查  是否允许探测
{
	if (entry._row >= 0 && entry._col >= 0
		&& entry._row < n && entry._col < n
		&& maze[entry._row * n + entry._col] == 0)
	{
		return true;
	} 
	else
	{
		return false;
	}
}

bool GetMazePath(int* maze,size_t n,Pos entry,stack<Pos>& path)//探测
{
	assert(maze);

	path.push(entry);
	maze[entry._row * n + entry._col] = 2;

	while (!path.empty())
	{
		Pos cur = path.top();
		if (cur._row == n-1 || cur._col == n-1)
		{
			return true;
		}

		//上
		Pos next = cur;
		next._row--;
		if (CheckIsAccess(maze,n,next))
		{
			maze[next._row * n + next._col] = 2;
			path.push(next);
			continue;
		}

		//右
		next = cur;
		next._col++;
		if (CheckIsAccess(maze,n,next))
		{
			maze[next._row * n + next._col] = 2;
			path.push(next);
			continue;
		}

		//下
		next = cur;
		next._row++;
		if (CheckIsAccess(maze,n,next))
		{
			maze[next._row * n + next._col] = 2;
			path.push(next);
			continue;
		}

		//左
		next = cur;
		next._col--;
		if (CheckIsAccess(maze,n,next))
		{
			maze[next._row * n + next._col] = 2;
			path.push(next);
			continue;
		}

		path.pop();
	}
	return false;
}</strong></span>


 

test.cpp

<span style="font-size:18px;"><strong>#define _CRT_SECURE_NO_WARNINGS 1
#include "maze.h"

void test()
{
	int maze[10][10] = {};
	InitMaze((int* )maze,10);
	PrintMaze((int* )maze,10);

	Pos entry = {2,0};//入口给定maze[2][0]
	stack<Pos> path;//需要栈的协助
	GetMazePath((int* )maze,10,entry,path);
	PrintMaze((int* )maze,10);

}
int main()
{
	test();
	system("pause");
	return 0;
}</strong></span>

《数据结构——迷宫问题》

《数据结构——迷宫问题》

《数据结构——迷宫问题》

《数据结构——迷宫问题》

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/poison_biti/article/details/51722370
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞