以下是一个用C语言编写的栈的迷宫旅行游戏代码示例,包括成功路径和图案。 ```c #include <stdio.h> #include <stdbool.h> #define ROW 6 #define COL 6 typedef struct { int row; int col; } Position; typedef struct { Position pos[100]; int top; } Stack; void init(Stack *s) { s->top = -1; } bool isEmpty(Stack s) { return s.top == -1; } bool isFull(Stack s) { return s.top == 100; } void push(Stack *s, Position p) { if (isFull(*s)) { printf("Stack is full!\n"); return; } s->pos[++s->top] = p; } Position pop(Stack *s) { if (isEmpty(*s)) { printf("Stack is empty!\n"); Position p = {-1, -1}; return p; } return s->pos[s->top--]; } bool isValidMove(int maze[ROW][COL], int row, int col) { return row >= 0 && row < ROW && col >= 0 && col < COL && maze[row][col] == 1; } bool solveMaze(int maze[ROW][COL], Position start, Position end) { Stack s; init(&s); int visited[ROW][COL] = {0}; visited[start.row][start.col] = 1; push(&s, start); int row, col, nextRow, nextCol; while (!isEmpty(s)) { Position curr = pop(&s); row = curr.row; col = curr.col; if (row == end.row && col == end.col) { return true; // Found the path } // Move up nextRow = row - 1; nextCol = col; if (isValidMove(maze, nextRow, nextCol) && !visited[nextRow][nextCol]) { Position next = {nextRow, nextCol}; push(&s, next); visited[nextRow][nextCol] = 1; } // Move down nextRow = row + 1; nextCol = col; if (isValidMove(maze, nextRow, nextCol) && !visited[nextRow][nextCol]) { Position next = {nextRow, nextCol}; push(&s, next); visited[nextRow][nextCol] = 1; } // Move left nextRow = row; nextCol = col - 1; if (isValidMove(maze, nextRow, nextCol) && !visited[nextRow][nextCol]) { Position next = {nextRow, nextCol}; push(&s, next); visited[nextRow][nextCol] = 1; } // Move right nextRow = row; nextCol = col + 1; if (isValidMove(maze, nextRow, nextCol) && !visited[nextRow][nextCol]) { Position next = {nextRow, nextCol}; push(&s, next); visited[nextRow][nextCol] = 1; } } return false; // No path found } void printMaze(int maze[ROW][COL]) { for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { printf("%d ", maze[i][j]); } printf("\n"); } } void printPath(Stack s) { int maze[ROW][COL] = { {1, 1, 0, 1, 1, 1}, {1, 1, 0, 0, 1, 1}, {1, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 1, 1}, {1, 1, 1, 1, 1, 1}, {0, 0, 0, 1, 1, 1} }; while (!isEmpty(s)) { Position p = pop(&s); maze[p.row][p.col] = 2; } printMaze(maze); } int main() { int maze[ROW][COL] = { {1, 1, 0, 1, 1, 1}, {1, 1, 0, 0, 1, 1}, {1, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 1, 1}, {1, 1, 1, 1, 1, 1}, {0, 0, 0, 1, 1, 1} }; Position start = {0, 0}; Position end = {5, 5}; if (solveMaze(maze, start, end)) { printf("Path found!\n"); Stack path; init(&path); push(&path, end); printPath(path); } else { printf("Path not found!\n"); } return 0; } ``` 在这个示例中,迷宫被建模为一个6x6的矩阵。1表示可以通过的位置,0表示墙壁。游戏从起点(0, 0)开始,目标是到达终点(5, 5)。 程序使用一个栈来跟踪当前的位置,并将其推入栈中。算法每次迭代时,将搜索当前位置的邻居,并尝试将其推入栈中。如果找到了终点,算法返回true,否则返回false。 在成功找到路径后,通过修改迷宫矩阵,将路径上的位置标记为2。调用`printMaze`函数打印迷宫,以显示最终路径。 [2024-06-17 19:48:16 | AI写代码神器 | 2702点数解答]