#include <iostream> #include <stack> #include <cstdlib> #include <ctime> using namespace std; const int MAXN = 100; const char WALL = '#'; const char PATH = ' '; const char START = 'S'; const char END = 'E'; const int dx[4] = { -1, 0, 1, 0 }; const int dy[4] = { 0, 1, 0, -1 }; int n, m; char maze[MAXN][MAXN]; bool vis[MAXN][MAXN]; stack<pair<int, int>> st; void init() { // 随机生成迷宫 srand(time(NULL)); n = rand() % 10 + 5; m = rand() % 10 + 5; int sx = rand() % n; int sy = rand() % m; int ex = rand() % n; int ey = rand() % m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i == sx && j == sy) maze[i][j] = START; else if (i == ex && j == ey) maze[i][j] = END; else if (rand() % 4 == 0) maze[i][j] = WALL; else maze[i][j] = PATH; } } } void print() { // 输出迷宫 cout << "Maze:" << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << maze[i][j] << ' '; } cout << endl; } } bool dfs(int x, int y) { // 深度优先搜索 vis[x][y] = true; st.push(make_pair(x, y)); if (maze[x][y] == END) { return true; } for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] != WALL && !vis[nx][ny]) { if (dfs(nx, ny)) { return true; } } } st.pop(); return false; } void solve() { // 求解迷宫 memset(vis, false, sizeof(vis)); while (!st.empty()) st.pop(); dfs(0, 0); } void print_path() { // 输出路径 cout << "Path:" << endl; while (!st.empty()) { auto p = st.top(); st.pop(); cout << '(' << p.first << ", " << p.second << ')' << endl; } } int main() { init(); print(); solve(); print_path(); return 0; } 为这段代码绘制一份完整的程序结构图
时间: 2024-01-29 18:02:18 浏览: 71
下面是程序的完整结构图:
```
+------------------------+
| main() |
+------------------------+
|
v
+------------------------+
| init() |
+------------------------+
|
v
+------------------------+
| print() |
+------------------------+
|
v
+------------------------+
| solve() |
+------------------------+
|
v
+------------------------+
| print_path() |
+------------------------+
```
其中,`init()` 函数用于随机生成迷宫,`print()` 函数用于输出迷宫,`solve()` 函数用于求解迷宫,`print_path()` 函数用于输出路径。在 `main()` 函数中,我们首先调用 `init()` 函数生成迷宫,然后调用 `print()` 函数输出迷宫。接着,调用 `solve()` 函数求解迷宫,最后调用 `print_path()` 函数输出路径。
阅读全文