用栈解决迷宫问题(输出所有路径和最短路径)

本文详细介绍了一种基于栈的迷宫寻路算法,通过递归回溯寻找从起点到终点的所有可能路径,并最终确定最短路径。文章通过具体代码实现展示了算法的工作原理,包括路径的记录、方向的选择及路径长度的比较。
#include<iostream>
#include<cstdio>
using namespace std;
#define M 4  //行数
#define N 4     //列数
#define MaxSize    100     //栈最多元素个数
int mg[M+2][N+2]= {
     {1,1,1,1,1,1}
    ,{1,0,0,0,1,1}
    ,{1,0,1,0,0,1}
    ,{1,0,0,0,1,1}
    ,{1,1,0,0,0,1}
    ,{1,1,1,1,1,1}
};
struct migong
{
    int i;      //路径横坐标
    int j;      //路径纵坐标
    int di;     //方向
} Stack[MaxSize],Path[MaxSize];     //定义栈和存放最短路径的数组
int top=-1;     //栈顶指针
int count=1;    //路径数计数
int minlen=MaxSize;     //最短路径长度
void mgpath()       //路径为:(1,1)->(M,N)
{
    int i,j,di,find,k;
    top++;
    Stack[top].i=1;
    Stack[top].j=1;
    Stack[top].di=-1;
    mg[1][1]=-1;        //初始结点进栈
    while(top>-1)       //栈不空时循环
    {
        i=Stack[top].i;
        j=Stack[top].j;
        di=Stack[top].di;
        if(i==M && j==N)        //找到了出口,输出路径
        {
            cout<<count<<": ";
            count++;
            for(k=0; k<=top; k++)
            {
                cout<<"("<<Stack[k].i<<","<<Stack[k].j<<")"<<" ";

            }
            cout<<endl;
            if(top+1<minlen)        //比较输出最短路径
            {
                for(k=0; k<=top; k++)
                    Path[k]=Stack[k];
                minlen=top+1;
            }
            mg[Stack[top].i][Stack[top].j]=0;   //让该位置变为其他路径的可走结点
            top--;
            i=Stack[top].i;
            j=Stack[top].j;
            di=Stack[top].di;
        }
        find=0;
        while(di<4 && find==0)      //找下一个可走结点
        {
            di++;
            switch(di)
            {
            case 0:
                i=Stack[top].i-1;
                j=Stack[top].j;
                break;   //上面
            case 1:
                i=Stack[top].i;
                j=Stack[top].j+1;
                break;   //右边
            case 2:
                i=Stack[top].i+1;
                j=Stack[top].j;
                break;   //下面
            case 3:
                i=Stack[top].i;
                j=Stack[top].j-1;
                break;   //左边
            }
            if(mg[i][j]==0)
                find=1;
        }
        if(find == 1)       //找到了下一个可走结点
        {
            Stack[top].di=di;   //修改原栈顶元素的di值
            top++;      //下一个可走结点进栈
            Stack[top].i=i;
            Stack[top].j=j;
            Stack[top].di=-1;
            mg[i][j]=-1;        //避免重复走到该结点
        }
        else
        {
            mg[Stack[top].i][Stack[top].j]=0;   //让该位置变为其他路径的可走结点
            top--;
        }
    }
    cout<<"最短路径如下"<<endl;
    cout<<"长度:  "<<minlen<<endl;
    cout<<"路径:  "<<endl;
    for(k=0; k<minlen; k++)
    {
       cout<<"("<<Path[k].i<<","<<Path[k].j<<")"<<" ";
    }
}
int main()
{
    cout<<"迷宫所有路径如下:"<<endl;
    mgpath();
    return 0;
}

 

以下是一个使用C语言,利用求解迷宫问题的所有路径最短路径的代码示例: ```c #include <stdio.h> #include <stdlib.h> #define MAX_ROWS 100 #define MAX_COLS 100 // 定义的结构体 typedef struct { int x; int y; } Point; typedef struct { Point data[MAX_ROWS * MAX_COLS]; int top; } Stack; // 初始化 void initStack(Stack *s) { s->top = -1; } // 判断是否为空 int isEmpty(Stack *s) { return s->top == -1; } // 入操作 void push(Stack *s, Point p) { s->data[++(s->top)] = p; } // 出操作 Point pop(Stack *s) { return s->data[(s->top)--]; } // 获取顶元素 Point top(Stack *s) { return s->data[s->top]; } // 判断点是否在迷宫范围内且无障碍 int isValid(int maze[MAX_ROWS][MAX_COLS], int rows, int cols, int x, int y) { return x >= 0 && x < rows && y >= 0 && y < cols && maze[x][y] == 0; } // 深度优先搜索求解迷宫所有路径最短路径 void findPaths(int maze[MAX_ROWS][MAX_COLS], int rows, int cols, int x, int y, Stack *path, Stack *shortestPath, int *minLength) { if (x == rows - 1 && y == cols - 1) { push(path, (Point){x, y}); if (path->top + 1 < *minLength) { *minLength = path->top + 1; for (int i = 0; i <= path->top; i++) { shortestPath->data[i] = path->data[i]; } shortestPath->top = path->top; } // 输出当前路径 printf("Path found:\n"); for (int i = 0; i <= path->top; i++) { printf("(%d, %d) ", path->data[i].x + 1, path->data[i].y + 1); } printf("\n"); pop(path); return; } push(path, (Point){x, y}); maze[x][y] = 2; // 标记为已访问 // 四个方向:上、下、左、右 int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; for (int i = 0; i < 4; i++) { int newX = x + dx[i]; int newY = y + dy[i]; if (isValid(maze, rows, cols, newX, newY)) { findPaths(maze, rows, cols, newX, newY, path, shortestPath, minLength); } } maze[x][y] = 0; // 回溯,恢复为未访问 pop(path); } int main() { int maze[MAX_ROWS][MAX_COLS]; int rows, cols; // 输入迷宫的行数列数 printf("Enter the number of rows and columns of the maze: "); scanf("%d %d", &rows, &cols); // 输入迷宫信息 printf("Enter the maze (0 for open, 1 for blocked):\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { scanf("%d", &maze[i][j]); } } Stack path, shortestPath; initStack(&path); initStack(&shortestPath); int minLength = MAX_ROWS * MAX_COLS; // 从起点开始搜索 findPaths(maze, rows, cols, 0, 0, &path, &shortestPath, &minLength); // 输出最短路径 if (minLength == MAX_ROWS * MAX_COLS) { printf("No path found.\n"); } else { printf("Shortest path:\n"); for (int i = 0; i <= shortestPath.top; i++) { printf("(%d, %d) ", shortestPath.data[i].x + 1, shortestPath.data[i].y + 1); } printf("\n"); } return 0; } ``` ### 代码说明: 1. **的实现**:定义了的结构体相关操作,如初始化、入、出等。 2. **深度优先搜索**:使用递归的深度优先搜索算法来遍历迷宫,找出所有可能的路径。 3. **最短路径筛选**:在找到出口时,比较当前路径的长度已记录的最短路径长度,更新最短路径。 ###
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值