如题,迷宫效果:
#include <stack>
#include <vector>
#include <iostream>
#include "time.h"
#include "stdlib.h"
using namespace std;
class MazeCell {
public:
bool right, down;
bool visited;
int x, y;
MazeCell() : x(0), y(0), right(true), down(true), visited(false) {}
};
class Maze {
private:
int row, col;
vector<vector<MazeCell>> table;
pair<int, int> GetNeighborCell(int x, int y) {
vector<pair<int, int>> avail;
if (x > 0 && !table[x - 1][y].visited) avail.push_back(pair<int, int>(x - 1, y));
if (y > 0 && !table[x][y - 1].visited) avail.push_back(pair<int, int>(x, y - 1));
if (x < row - 1 && !table[x + 1][y].visited) avail.push_back(pair<int, int>(x + 1, y));
if (y < col - 1 && !table[x][y + 1].visited) avail.push_back(pair<int, int>(x, y + 1));
if (!avail.size()) return pair<int, int>(x, y);
return avail[rand() % avail.size()];
}
public:
Maze(int r, int c) : row(r), col(c) {}
~Maze() {}
void Build() {
stack<pair<int, int>> s;
pair<int, int> curr, p;
table.clear();
table = vector<vector<MazeCell>>(row, vector<MazeCell>(col, MazeCell()));
for (int i = 0;i < row;++i) {
for (int j = 0;j < col;++j) {
table[i][j].x = i;
table[i][j].y = j;
}
}
srand(time(0));
s.push(pair<int, int>(0, 0));
table[0][0].visited = true;
while (!s.empty()) {
curr = s.top();
//cout<<"current point: ("<<curr.first<<","<<curr.second<<")"<<endl;
p = GetNeighborCell(curr.first, curr.second);
//cout<<"next point: ("<<p.first<<","<<p.second<<")"<<endl;
if (p.first == curr.first && p.second == curr.second) s.pop();
else {
s.push(p);
table[p.first][p.second].visited = true;
if (p.first == curr.first - 1)
table[p.first][p.second].down = false;
else if (p.first == curr.first + 1)
table[curr.first][curr.second].down = false;
else if (p.second == curr.second - 1)
table[p.first][p.second].right = false;
else if (p.second == curr.second + 1)
table[curr.first][curr.second].right = false;
}
}
}
void Print() {
for (int i = 0;i < row;i++) {
for (int j = 0;j < col;j++) {
if (table[i][j].down) cout<<"_";
else cout<<" ";
if (table[i][j].right) cout<<"|";
else cout<<" ";
}
cout<<endl;
}
}
};
int main(int argc, char **argv)
{
Maze m(20, 10);
m.Build();
m.Print();
int x; cin>>x;
return 0;
}