【資料結構】走迷宮實現
阿新 • • 發佈:2019-01-27
#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