好的,下面是一个简单的 C++ 迷宫游戏示例:
```c++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
const int MAX_ROW = 6;
const int MAX_COL = 6;
struct Point {
int row, col;
Point(int r, int c) : row(r), col(c) {}
};
bool isValid(Point& p) {
if (p.row < 0 || p.col < 0 || p.row >= MAX_ROW || p.col >= MAX_COL) {
return false;
}
return true;
}
bool isWall(Point& p) {
int maze[MAX_ROW][MAX_COL] = {
{0, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 1, 0},
{0, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 0},
{0, 0, 0, 0, 0, 0},
};
return maze[p.row][p.col] == 1;
}
void printPath(stack<Point>& path) {
cout << "Path: ";
while (!path.empty()) {
Point p = path.top();
cout << "(" << p.row << "," << p.col << ") ";
path.pop();
}
cout << endl;
}
bool dfs(Point& start, Point& end, stack<Point>& path) {
if (!isValid(start) || !isValid(end) || isWall(start) || isWall(end)) {
return false;
}
if (start.row == end.row && start.col == end.col) {
path.push(start);
return true;
}
int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int i = 0; i < 4; i++) {
Point next(start.row + directions[i][0], start.col + directions[i][1]);
if (isValid(next) && !isWall(next)) {
path.push(start);
if (dfs(next, end, path)) {
return true;
}
path.pop();
}
}
return false;
}
int main() {
Point start(1, 1);
Point end(4, 4);
stack<Point> path;
if (dfs(start, end, path)) {
printPath(path);
} else {
cout << "No path found!" << endl;
}
return 0;
}
```
在这个示例中,我们使用深度优先搜索(DFS)算法来找到从起点到终点的路径。我们定义了一个 `Point` 结构体来表示迷宫中的每个点,其中包含行和列的索引。我们还定义了 `isValid` 函数来检查一个点是否在迷宫中,`isWall` 函数来检查一个点是否是墙,以及 `printPath` 函数来打印路径。最重要的是,我们定义了 `dfs` 函数来使用 DFS 算法来查找路径。它从起点开始,逐步遍历迷宫中的每个可访问点,直到找到终点或无法继续前进。如果找到路径,则将其存储在堆栈中,最终打印出来。
请注意,示例中的迷宫是一个硬编码的数组,但实际上您可以从文件或用户输入中读取迷宫。此外,您可以使用其他算法(如广度优先搜索)或改进算法来提高性能。