c语言给定一迷宫以及入口和出口的坐标,要求寻找从入口到出口的最短距离。要求用到队列以及广度搜索来求

比如下图假如入中是(0,0),出口是(1,7)黄色代表墙,白色代表通路,则从入口到出口的最短需要走8步。

img

求解答

引用chatgpt内容作答:
以下是一个使用广度优先搜索(BFS)算法来解决迷宫问题的C语言代码示例:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_SIZE 45

typedef struct {
    int row;
    int col;
} Coordinate;

typedef struct {
    Coordinate coordinates[MAX_SIZE * MAX_SIZE];
    int front;
    int rear;
} Queue;

// 初始化队列
void initQueue(Queue *queue) {
    queue->front = queue->rear = -1;
}

// 判断队列是否为空
bool isQueueEmpty(Queue *queue) {
    return queue->front == -1;
}

// 入队
void enqueue(Queue *queue, Coordinate coord) {
    if (isQueueEmpty(queue))
        queue->front = 0;
    queue->rear++;
    queue->coordinates[queue->rear] = coord;
}

// 出队
Coordinate dequeue(Queue *queue) {
    Coordinate coord = queue->coordinates[queue->front];
    if (queue->front == queue->rear)
        initQueue(queue);
    else
        queue->front++;
    return coord;
}

// 判断坐标是否合法
bool isValidCoordinate(int row, int col, int m, int n) {
    return row >= 0 && row < m && col >= 0 && col < n;
}

// 判断坐标是否为终点
bool isDestination(Coordinate coord, Coordinate destination) {
    return coord.row == destination.row && coord.col == destination.col;
}

// 寻找最短路径长度
int findShortestPath(int maze[MAX_SIZE][MAX_SIZE], int m, int n, Coordinate start, Coordinate destination) {
    int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 上下左右四个方向的偏移量

    bool visited[MAX_SIZE][MAX_SIZE] = {{false}}; // 记录每个坐标是否已访问
    visited[start.row][start.col] = true;

    Queue queue;
    initQueue(&queue);
    enqueue(&queue, start);

    int steps = 0; // 起点到当前坐标的步数

    while (!isQueueEmpty(&queue)) {
        int numNodesInLevel = queue.rear - queue.front + 1;

        while (numNodesInLevel > 0) {
            Coordinate current = dequeue(&queue);

            if (isDestination(current, destination))
                return steps;

            for (int i = 0; i < 4; i++) {
                int newRow = current.row + directions[i][0];
                int newCol = current.col + directions[i][1];

                if (isValidCoordinate(newRow, newCol, m, n) && maze[newRow][newCol] == 0 && !visited[newRow][newCol]) {
                    visited[newRow][newCol] = true;
                    Coordinate newCoord = {newRow, newCol};
                    enqueue(&queue, newCoord);
                }
            }

            numNodesInLevel--;
        }

        steps++;
    }

    return -1; // 无法到达终点
}

int main() {
    int m, n;
    scanf("%d %d", &m, &n);

    int maze[MAX_SIZE][MAX_SIZE];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &maze[i][j]);
        }
    }

    Coordinate start, destination;
    scanf("%d %d %d %d", &start.row, &start.col, &destination.row, &destination.col);

    int shortestPathLength = findShortestPath(maze, m, n, start, destination);

    if (shortestPathLength == -1)
        printf("nopath!\n");
    else
        printf("%d\n", shortestPathLength);

    return 0;
}

这个代码示例读取迷宫的大小、迷宫的内容以及起点和终点的坐标。然后使用广度优先搜索算法找到从起点到终点的最短路径长度,并输出结果。如果无法到达终点,则输出"nopath!"。请注意,代码中使用了一个队列来辅助实现广度优先搜索。

广度优先算法经典:迷宫最短路径问题(C语言实现)_c语言求迷宫最短路径_吃土男孩_的博客-CSDN博客 今年上半年蓝桥杯考了类似的题(基本一样),本人算法菜鸡,考场上头铁用深搜写这个导致爆栈,最近闲下来研究了一下,写了一个找到最短出路的demo问题描述  学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗。但学霸为了不要别人打扰,住在一个城堡里,城堡外面是一个二维的格子迷宫,要进城堡必须得先通过迷宫。因为班长还有妹子要陪,磨刀不误砍柴功,他为了节约时间,从线人那里搞到了迷宫的地..._c语言求迷宫最短路径 https://blog.csdn.net/qq_40761320/article/details/92800325

img


#include <stdio.h>
#include <stdbool.h>

#define MAX_SIZE 45

// 定义坐标结构体
typedef struct {
    int x;
    int y;
} Point;

// 定义队列结构体
typedef struct {
    Point data[MAX_SIZE];
    int front;
    int rear;
} Queue;

// 初始化队列
void initQueue(Queue* queue) {
    queue->front = 0;
    queue->rear = 0;
}

// 入队操作
void enqueue(Queue* queue, Point point) {
    queue->data[queue->rear++] = point;
}

// 出队操作
Point dequeue(Queue* queue) {
    return queue->data[queue->front++];
}

// 判断队列是否为空
bool isEmpty(Queue* queue) {
    return queue->front == queue->rear;
}

// 判断坐标是否合法
bool isValid(Point point, int m, int n) {
    return point.x >= 0 && point.x < m&& point.y >= 0 && point.y < n;
}

// 寻找从入口到出口的最短路径
int findShortestPath(int maze[MAX_SIZE][MAX_SIZE], int m, int n, Point start, Point end) {
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    Queue queue;
    bool visited[MAX_SIZE][MAX_SIZE] = { false };
    int distance[MAX_SIZE][MAX_SIZE] = { 0 };

    initQueue(&queue);
    enqueue(&queue, start);
    visited[start.x][start.y] = true;

    while (!isEmpty(&queue)) {
        Point current = dequeue(&queue);
        if (current.x == end.x && current.y == end.y) {
            return distance[current.x][current.y];
        }

        for (int i = 0; i < 4; i++) {
            Point next = { current.x + dx[i], current.y + dy[i] };
            if (isValid(next, m, n) && maze[next.x][next.y] == 0 && !visited[next.x][next.y]) {
                enqueue(&queue, next);
                visited[next.x][next.y] = true;
                distance[next.x][next.y] = distance[current.x][current.y] + 1;
            }
        }
    }

    return -1; // 无路径的情况
}

int main() {
    int m, n;
    int maze[MAX_SIZE][MAX_SIZE];
    Point start, end;

    printf("请输入迷宫的行数和列数:\n");
    scanf("%d %d", &m, &n);

    printf("请输入迷宫的布局:\n");
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &maze[i][j]);
        }
    }

    scanf("%d %d %d %d", &start.x, &start.y,&end.x, &end.y);

    int shortestPath = findShortestPath(maze, m, n, start, end);

    if (shortestPath == -1) {
        printf("no path!\n");
    }
    else {
        printf("从起点到终点的最短路径长度为:%d\n", shortestPath);
    }

    return 0;
}

这是个c语言实现队列和BFS的例子,你可以根据实际题目做修改。
用于存放迷宫地图坐标的队列数据结构:

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100

typedef struct {
    int x;
    int y;
} Point;

typedef struct {
    Point data[MAXSIZE];
    int front;
    int rear;
} Queue;

void initQueue(Queue *q) {
    q->front = 0;
    q->rear = 0;
}

int isEmpty(Queue *q) {
    return q->front == q->rear;
}

int isFull(Queue *q) {
    return (q->rear + 1) % MAXSIZE == q->front;
}

void enQueue(Queue *q, Point p) {
    if (isFull(q)) {
        printf("Queue is full!\n");
        exit(1);
    }
    q->data[q->rear] = p;
    q->rear = (q->rear + 1) % MAXSIZE;
}

Point deQueue(Queue *q) {
    if (isEmpty(q)) {
        printf("Queue is empty!\n");
        exit(1);
    }
    Point p = q->data[q->front];
    q->front = (q->front + 1) % MAXSIZE;
    return p;
}

BFS搜索迷宫:

int maze[5][5] = {
    {0, 1, 0, 0, 0},
    {0, 1, 0, 1, 0},
    {0, 0, 0, 0, 0},
    {0, 1, 1, 1, 0},
    {0, 0, 0, 1, 0}
};

int visited[5][5] = {0};

int isValid(int x, int y) {
    if (x < 0 || x >= 5 || y < 0 || y >=5 || maze[x][y] == 1 || visited[x][y] == 1) {
        return 0;
    }
    return 1;
}

void bfs(int startX, int startY) {
    Queue q;
    initQueue(&q);
    
    Point start = {startX, startY};
    enQueue(&q,start);
    
    while (!isEmpty(&q)) {
        Point p = deQueue(&q);
        visited[p.x][p.y] = 1;
        
        if (p.x == 4 && p.y ==4) {
            printf("Find the exit!\n");
            return;
        }
        
        if (isValid(p.x-1,p.y)) {
            Point newP = {p.x-1,p.y};
            enQueue(&q,newP);
        }
        if (isValid(p.x+1,p.y)) {
            Point newP = {p.x+1,p.y};
            enQueue(&q,newP);
        }
        if (isValid(p.x,p.y-1)) {
            Point newP = {p.x,p.y-1};
            enQueue(&q,newP);
        }
        if (isValid(p.x,p.y+1)) {
            Point newP = {p.x,p.y+1};
            enQueue(&q,newP);
        }
        
    }
    
}

int main() {
    
    bfs(0,0);
    
}