#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