c++走迷宫小游戏代码
时间: 2023-09-04 22:07:58 浏览: 144
以下是使用深度优先搜索算法实现的C++走迷宫小游戏代码示例:
```c++
#include <iostream>
#include <stack>
using namespace std;
const int MAXN = 10;
int maze[MAXN][MAXN] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
struct Node {
int x, y, dir;
};
stack<Node> s;
int main() {
Node start = {1, 1, 1};
s.push(start);
while (!s.empty()) {
Node cur = s.top();
s.pop();
int x = cur.x, y = cur.y, dir = cur.dir;
while (dir <= 4) {
int dx = 0, dy = 0;
switch (dir) {
case 1: // 向上
dx = -1;
break;
case 2: // 向右
dy = 1;
break;
case 3: // 向下
dx = 1;
break;
case 4: // 向左
dy = -1;
break;
}
int nx = x + dx, ny = y + dy;
if (maze[nx][ny] == 0) { // 可以走
Node next = {nx, ny, 1};
s.push(cur);
s.push(next);
maze[nx][ny] = 1; // 标记为已走过
x = nx, y = ny;
dir = 1;
if (x == MAXN - 2 && y == MAXN - 2) { // 到达终点
cout << "Successful!" << endl;
return 0;
}
}
else { // 不可走
++dir;
}
}
}
cout << "Failed!" << endl;
return 0;
}
```
该代码使用了一个栈来模拟深度优先搜索的过程,每次从栈中取出一个节点进行扩展,如果可以走就将该节点和下一个节点入栈,否则就尝试下一个方向。当找到终点时输出成功,否则输出失败。
阅读全文