#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <initializer_list>
#include <deque>
#include <list>
#include <array>
#include <forward_list>
#include <sstream>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <memory>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <type_traits>
#include <utility>
#include <tuple>
#include <bitset>
#include <regex>
#include <random>
#include <iomanip>
#include <ctime>
#include <cmath>
#define ERROR nullptr
using namespace::std;
struct MazePosition;
using ElementType = MazePosition;
typedef int Position;
struct SNode;
typedef SNode* PtrToSNode;
using Stack = PtrToSNode;
#define MAXMATRIXSIZE 10
#define MAXSTACKSIZE 100
struct Offsets {
short Vert;
short Horiz;
};
struct MazePosition {
short Row;
short Col;
short Dir;
};
void Path(int Maze[][MAXMATRIXSIZE], int EXITROW, int EXITCOL)
{
Offsets Move[8] = { {-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1} };
int Mark[MAXMATRIXSIZE][MAXMATRIXSIZE];
for (auto i = 0; i != MAXMATRIXSIZE; ++i)
for (auto j = 0; j != MAXMATRIXSIZE; ++j)
Mark[i][j] = 0;
MazePosition P;
vector<MazePosition> S;
short Row, Col, NextRow, NextCol, Dir;
bool Found = false;
Mark[EXITROW][EXITCOL] = 1;
P.Row = EXITROW;
P.Col = EXITCOL;
P.Dir = 0;
S.push_back(P);
while (!S.empty() && !Found)
{
P = S.back();
S.pop_back();//程序设计有问题
Row = P.Row;
Col = P.Col;
Dir = P.Dir;
while (Dir < 8 && !Found)
{
NextRow = Row + Move[Dir].Vert;
NextCol = Col + Move[Dir].Horiz;
if (NextRow == 1 && NextCol == 1)
Found = true;
else
if (!Maze[NextRow][NextCol] && !Mark[NextRow][NextCol])
{
Mark[NextRow][NextCol] = 1;
P.Row = Row;
P.Col = Col;
P.Dir = P.Dir + 1;
S.push_back(P);
Row = NextRow;
Col = NextCol;
Dir = 0;
}
else
++Dir;
}
}
if (Found)
{
cout << "The Path is as following:" << endl;
cout << "Row Col" << endl;
cout << "1 1" << endl;
cout << Row << " "<<Col << endl;
while (!S.empty())
{
P = S.back();
S.pop_back();
cout << P.Row << " " << P.Col << endl;
}
}
else
{
cout << "The maze is lack of solution." << endl;
}
}
void showmaze(int maze[MAXMATRIXSIZE][MAXMATRIXSIZE])
{
for (auto i = 0; i != MAXMATRIXSIZE; ++i)
{
for (auto j = 0; j != MAXMATRIXSIZE; ++j)
{
cout << maze[i][j];
}
cout << endl;
}
}
int main()
{
int maze[MAXMATRIXSIZE][MAXMATRIXSIZE];
default_random_engine e;
uniform_int_distribution<int> u(0, 1);
e.seed(time(0));
for(auto i=0;i!=MAXMATRIXSIZE;++i)
for (auto j = 0; j != MAXMATRIXSIZE; ++j)
{
maze[i][j] = u(e);
}
for (auto i = 0; i != MAXMATRIXSIZE; ++i)
{
maze[0][i] = 1;
maze[MAXMATRIXSIZE - 1][i] = 1;
maze[i][0] = 1;
maze[i][MAXMATRIXSIZE-1] = 1;
}
maze[1][1] = 0;
showmaze(maze);
int exitrow = 5;
int exitcol=7;
Path(maze, exitrow,exitcol);
return 0;
}
数据结构第三章迷宫代码
最新推荐文章于 2021-09-14 12:23:50 发布