【数据结构】走迷宫实现

#pragma once
#ifndef _MAZE_H_
#define _MAZE_H_

struct Intersection {
	int left, forwd, right;    	//路口信息
};

struct Maze {
	int MazeSize;	             	//迷宫大小(路口数)
	int EXIT;			//出口号码       
	Intersection *intsec;   		//路口数组
};

#endif

#include "Maze.h"
#include <fstream>
#include <iostream>
#include<stack>
using namespace std;

bool GetMaze(char *filename, struct Maze &M)
{//读取迷宫数据:从文件 filename 中读取各路口
 //和出口的数据  
	ifstream fin;
	fin.open(filename, ios::in);//为输入打开文件,文件不存在则打开失败  
	if (!fin)
	{
		cout << "迷宫数据文件" << filename << "打不开" << endl;
		return false;
	}
	fin >> M.MazeSize;//输入迷宫路口数
	M.intsec = new Intersection[M.MazeSize + 1];//创建迷宫路口数组
	for (int i = 1; i <= M.MazeSize; i++)
		fin >> M.intsec[i].left >> M.intsec[i].forwd >> M.intsec[i].right;
	fin >> M.EXIT;  //输入迷宫出口
	fin.close();
	return true;
}

bool Traverse(int Pos, const Maze& M, stack<int> &S)
{//迷宫漫游算法
	if (Pos > 0)
	{ //路口从 1 开始
		if (Pos == M.EXIT) //出口      	      
		{
			S.push(Pos);
			return 1;
		}
		else if (Traverse(M.intsec[Pos].left, M, S))//向左
		{
			S.push(Pos);
			return 1;
		}
		else if (Traverse(M.intsec[Pos].forwd, M, S))//向前
		{
			S.push(Pos);
			return 1;
		}
		else if (Traverse(M.intsec[Pos].right, M, S))//向右 
		{
			S.push(Pos);
			return 1;
		}
	}
	return 0;
}

void main()
{
	stack<int> S;
	Maze M;
	if (GetMaze("maze.txt", M))
		Traverse(1, M, S);
	int l = S.size();
	cout << "正确路径:" << endl;
	for (int i = 0; i<l; i++)
	{
		cout << S.top();
		S.pop();
	}
	cout << endl;
}

//Maze.txt
6
0 2 0
3 5 6
0 0 4
0 0 0
0 0 0
7 0 0
7

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值