用链表写一个迷宫老鼠的c++代码
时间: 2023-10-24 22:04:44 浏览: 93
用C++编写迷宫老鼠
好的,以下是用链表写迷宫老鼠的C代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 10
#define COL 10
#define START_ROW 0
#define START_COL 0
#define END_ROW 9
#define END_COL 9
typedef struct Node {
int x;
int y;
struct Node *next;
} Node;
Node *createNode(int x, int y) {
Node *node = (Node*) malloc(sizeof(Node));
node->x = x;
node->y = y;
node->next = NULL;
return node;
}
void printMaze(int maze[][COL], int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", maze[i][j]);
}
printf("\n");
}
}
int validMove(int maze[][COL], int row, int col, int x, int y, int visited[][COL]) {
if (x >= 0 && x < row && y >= 0 && y < col && maze[x][y] == 0 && visited[x][y] == 0) {
return 1;
}
return 0;
}
void findPath(int maze[][COL], int row, int col, int visited[][COL], Node *root, Node **result) {
if (root == NULL || *result != NULL) {
return;
}
visited[root->x][root->y] = 1;
if (root->x == END_ROW && root->y == END_COL) {
*result = root;
return;
}
if (validMove(maze, row, col, root->x, root->y + 1, visited)) {
Node *right = createNode(root->x, root->y + 1);
root->next = right;
findPath(maze, row, col, visited, right, result);
}
if (*result == NULL && validMove(maze, row, col, root->x + 1, root->y, visited)) {
Node *down = createNode(root->x + 1, root->y);
root->next = down;
findPath(maze, row, col, visited, down, result);
}
if (*result == NULL && validMove(maze, row, col, root->x, root->y - 1, visited)) {
Node *left = createNode(root->x, root->y - 1);
root->next = left;
findPath(maze, row, col, visited, left, result);
}
if (*result == NULL && validMove(maze, row, col, root->x - 1, root->y, visited)) {
Node *up = createNode(root->x - 1, root->y);
root->next = up;
findPath(maze, row, col, visited, up, result);
}
}
int main() {
int maze[ROW][COL] = {
{0, 1, 0, 0, 0, 0, 0, 0, 1, 0},
{0, 1, 0, 1, 1, 1, 1, 1, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 1, 1, 1, 1, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 1, 0},
{0, 1, 1, 1, 1, 1, 1, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 0}
};
int visited[ROW][COL] = {0};
Node *root = createNode(START_ROW, START_COL);
Node *result = NULL;
findPath(maze, ROW, COL, visited, root, &result);
if (result != NULL) {
printf("The path to the cheese:\n");
Node *node = root;
while (node != NULL) {
printf("(%d, %d) ", node->x, node->y);
node = node->next;
}
printf("\n");
} else {
printf("The cheese cannot be found.\n");
}
return 0;
}
```
这是一个使用链表实现的迷宫老鼠寻找奶酪的示例程序。它先初始化了一个迷宫数组和一个访问数组,然后从起点开始通过递归寻找到终点,并将路径保存在一个链表中。最后,程序输出路径或者提示无法找到奶酪。
阅读全文