急!数据结构迷宫问题!
请高手指教怎样写下列头文件的main函数!#include<iostream.h>#include<fstream.h>#include<stdlib.h>structI...
请高手指教怎样写下列头文件的main函数!
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
struct Intersection //交通路口结构定义
{
int left;
int forward;
int right;
};
class Maze //迷宫定义
{
private:
int MazeSize;
int EXIT;
Intersection *intsec;
public:
Maze(char *filename);
int TraverseMaze(int CurrentPos);
};
Maze :: Maze(char *filename) //构造函数:从文件 filename 中读取各路口和出口的数据
{
ifstream fin;
fin.open(filename, ios::in | ios::nocreate); //为输入打开文件,文件不存在则打开失败
if (!fin)
{
cerr << "迷宫数据文件" << filename<< "打不开" << endl;
exit(1);
}
fin >> MazeSize; //输入迷宫路口数
intsec = new Intersection[MazeSize+1]; //创建迷宫路口数组
for (int i = 1; i <= MazeSize; i++)
fin >> intsec[i].left >> intsec[i].forward>> intsec[i].right;
fin >> EXIT; //输入迷宫出口
fin.close();
}
int Maze::TraverseMaze(int CurrentPos)
{
if (CurrentPos > 0) //路口从 1 开始
{
if (CurrentPos == EXIT) //出口处理
{
cout << CurrentPos << " ";
return 1;
}
else
{
//递归向左搜寻可行
if (TraverseMaze(intsec[CurrentPos].left))
{
cout << CurrentPos <<" ";
return 1;
} //递归向前搜寻可行
if (TraverseMaze(intsec[CurrentPos].forward))
{
cout << CurrentPos << " ";
return 1;
}
//递归向右搜寻可行
if (TraverseMaze(intsec[CurrentPos].right))
{
cout << CurrentPos <<" ";
return 1;
}
}
}
return 0;
}; 展开
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
struct Intersection //交通路口结构定义
{
int left;
int forward;
int right;
};
class Maze //迷宫定义
{
private:
int MazeSize;
int EXIT;
Intersection *intsec;
public:
Maze(char *filename);
int TraverseMaze(int CurrentPos);
};
Maze :: Maze(char *filename) //构造函数:从文件 filename 中读取各路口和出口的数据
{
ifstream fin;
fin.open(filename, ios::in | ios::nocreate); //为输入打开文件,文件不存在则打开失败
if (!fin)
{
cerr << "迷宫数据文件" << filename<< "打不开" << endl;
exit(1);
}
fin >> MazeSize; //输入迷宫路口数
intsec = new Intersection[MazeSize+1]; //创建迷宫路口数组
for (int i = 1; i <= MazeSize; i++)
fin >> intsec[i].left >> intsec[i].forward>> intsec[i].right;
fin >> EXIT; //输入迷宫出口
fin.close();
}
int Maze::TraverseMaze(int CurrentPos)
{
if (CurrentPos > 0) //路口从 1 开始
{
if (CurrentPos == EXIT) //出口处理
{
cout << CurrentPos << " ";
return 1;
}
else
{
//递归向左搜寻可行
if (TraverseMaze(intsec[CurrentPos].left))
{
cout << CurrentPos <<" ";
return 1;
} //递归向前搜寻可行
if (TraverseMaze(intsec[CurrentPos].forward))
{
cout << CurrentPos << " ";
return 1;
}
//递归向右搜寻可行
if (TraverseMaze(intsec[CurrentPos].right))
{
cout << CurrentPos <<" ";
return 1;
}
}
}
return 0;
}; 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询