继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

栈的应用----走出迷宫

幕布斯6054654
关注TA
已关注
手记 1135
粉丝 218
获赞 1009

走出迷宫

#define _CRT_SECURE_N0_WARNINGS 1//规定 上3下1左2右4#include <iostream>#include <stack>using namespace std;#define ROWSIZE 10#define COLSIZE 10typedef int MazeType[ROWSIZE][COLSIZE];void PrintMaze(MazeType maze){    for (int i = 0; i < ROWSIZE; i++)
    {        for (int j = 0; j < COLSIZE; j++)            printf("%d ", maze[i][j]);        printf("\n");
    }
}typedef struct{
    int row;    int col;
}PosType;typedef struct{
    int ord;//步数
    PosType seat;//位置 
    int di;//1 2 3 4 方向}SelemType;bool Is_Pass(MazeType maze, PosType pos){    return maze[pos.row][pos.col] == 0;
}void FootPrint(MazeType maze, PosType pos){
    maze[pos.row][pos.col] = 8;
}void MarkPrint(MazeType maze, PosType pos){
    maze[pos.row][pos.col] = 4;
}PosType NextPos(PosType pos, int di){    switch (di)
    {    case 1:
        pos.row += 1;        break;    case 2:
        pos.col -= 1;        break;    case 3:
        pos.row -= 1;        break;    case 4:
        pos.col += 1;        break;    default:        break;
    }    return pos;
}void MazePath(MazeType maze,PosType begin, PosType end){
    PosType pos = begin;    int step = 0;
    SelemType e;    stack <SelemType> st;    
    do{        if (Is_Pass(maze, pos))
        {
            e.ord = ++step;
            e.seat = pos;
            e.di = 1;

            FootPrint(maze, pos);            if (pos.row == end.row && pos.col == end.col)                break;
            st.push(e);
            pos = NextPos(pos, 1);
        }        else
        {            if (!st.empty())
            {
                e=st.top(); st.pop();                while (e.di == 4 && !st.empty())
                {
                    MarkPrint(maze, e.seat);
                    e=st.top();
                    st.pop();
                }                if (e.di < 4)
                {
                    e.di++;
                    st.push(e);
                    pos = NextPos(e.seat, e.di);
                }
            }
        }

    } while (!st.empty());

}int main(){
    MazeType maze= {
        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 },
        { 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 },
        { 1, 0, 0, 0, 0, 1, 1, 0, 0, 1 },
        { 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 },
        { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
        { 1, 0, 1, 0, 0, 0, 1, 0, 0, 1 },
        { 1, 0, 1, 1, 1, 0, 1, 1, 0, 1 },
        { 1, 1, 0, 0, 0, 0, 0, 0, 0, 1 },
        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
    };
    PosType begin = {1,1};
    PosType end = {8,8};

    PrintMaze(maze);
    MazePath(maze,begin,end);    printf("-----------------------------\n");
    PrintMaze(maze);    return 0;
}



运行结果:

webp

image.png



作者:修夏之夏i
链接:https://www.jianshu.com/p/5181a491fc0d


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP