我正在创建一个迷宫游戏,该游戏将被机器遍历和解决 . 我创建了一个迷宫类,其中包含迷宫的起始位置和结束位置,以及包含在2d bool矢量中的迷宫本身 . 我正在惹恼的是如何实际编码上下移动和穿过迷宫来完成 . 我的起点是[11] [4]在迷宫中,我们的教授告诉我们,最好的方法是检查当前位置周围的所有4个位置,如果它是真的(也就是它是路径而不是墙)把它推到堆栈上 . 我从概念上理解这意味着什么,但我无法想象如何正确编码,任何帮助将不胜感激 . 仅供参考,有一个位置结构可以简化如何表达位置 .
struct Location {
friend std::ostream &operator <<(std::ostream &os, const Location &location) {
os << "(" << location.x << ", " << location.y << ")";
return os;
}
bool operator ==(const Location &rhs) const {return x == rhs.x && y == rhs.y;}
bool operator !=(const Location &rhs) const {return !(*this == rhs);}
operator bool() const {return x >= 0;}
Location(int x=-1, int y=-1) : x(x), y(y) {}
int x, y;
};
class Maze;
Maze load(std::string filename);
class Maze {
friend std::ostream &operator <<(std::ostream &os, Maze &maze);
friend Maze load(std::string filename);
public:
Maze(std::vector<std::vector<bool> > specifics, const Location &startPos, const Location &endPos);
bool solve();
//void run();
private:
bool contains(const Location &location) const;
bool isPath(const Location &location) const;
int height() {return spec.size();}
int width() {return spec[0].size();}
std::vector<std::vector<bool> > spec;
Location start, finish;
Location current;
};
bool Maze::solve() {
stack<Location> location; //vector to hold location objects/paths
Location current; //will hold current position in maze
current = start; //set current to start position in beginning
location.push(current); //push first maze location (start) onto vector
//cout << current;
///need to set current to top of stack; while traversing maze current is top of stack and if current hits (==) finish return true
while (!location.empty()) //while location still has values inside
{
current=location.top();//set current to top of stack
cout << current << endl;
cout << spec[6][4];
if (current==finish) //if current == finish the maze is solved
return true;
// for loop to start moving around... but how?
}
}
1 回答
这是一个伪代码;
Edit
这大致是代码(注意,我没有编译它)
您可能需要添加其他逻辑 . 显然你会进入无限循环,因为在进入之前我没有检查是否有任何单元格被访问过 . 不知何故,你必须记住它(可能是一个访问列表) .