C++代码编写迷宫问题
时间: 2024-01-04 13:03:58 浏览: 108
以下是C++实现迷宫问题的代码示例:
```cpp
#include <bits/stdc++.h>
#include <windows.h>
#include <conio.h>
#define ge srand(static_cast<int>(time(NULL)));
using namespace std;
const int MAXN = 1005;
const int MAXM = 1005;
int n, m;
int sx, sy, ex, ey;
int maze[MAXN][MAXM];
int vis[MAXN][MAXM];
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
struct node {
int x, y;
};
stack<node> s;
void gotoxy(int x, int y) {
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void setColor(int color) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void init() {
memset(maze, 0, sizeof(maze));
memset(vis, 0, sizeof(vis));
s = stack<node>();
}
void printMaze() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (maze[i][j] == 0) {
setColor(7);
cout << " ";
} else if (maze[i][j] == 1) {
setColor(0);
cout << "■";
} else if (maze[i][j] == 2) {
setColor(2);
cout << "★";
} else if (maze[i][j] == 3) {
setColor(4);
cout << "◆";
}
}
cout << endl;
}
}
bool dfs(int x, int y) {
vis[x][y] = 1;
s.push({x, y});
if (x == ex && y == ey) {
while (!s.empty()) {
node t = s.top();
s.pop();
maze[t.x][t.y] = 2;
printMaze();
Sleep(100);
}
return true;
}
for (int i = 0; i < 4; i++) {
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && !vis[nx][ny] && maze[nx][ny] == 0) {
if (dfs(nx, ny)) {
return true;
}
}
}
s.pop();
return false;
}
int main() {
ge;
init();
n = 10, m = 10;
sx = 1, sy = 1, ex = 10, ey = 10;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i == sx && j == sy) {
maze[i][j] = 0;
} else if (i == ex && j == ey) {
maze[i][j] = 0;
} else {
maze[i][j] = rand() % 2;
}
}
}
printMaze();
dfs(sx, sy);
setColor(7);
cout << "Press any key to continue..." << endl;
_getch();
return 0;
}
```
阅读全文