#include<stdio.h>
#include<stdlib.h> // rand
#include<assert.h>
#include<string.h>
#include<iostream>
using namespace std; // vs 2019
#include"MyStack.h"
typedef struct
{
int row;
int col;
}PosType;
typedef struct
{
int ord;
PosType seat;
int di; // 1 2 3 4
}SElemType;
#define ROWSIZE 10
#define COLSIZE 10
#define FOOT 8
#define MARK 4
typedef int MazeType[ROWSIZE][COLSIZE];
void Print_Maze(MazeType maze)
{
for (int i = 0; i < ROWSIZE; ++i)
{
for (int j = 0; j < COLSIZE; ++j)
{
printf("%2d", maze[i][j]);
}
printf("\n");
}
printf("\n");
}
void PathMaze(MazeType maze, PosType begin, PosType end)
{
PosType curpos = begin;
int curstep = 1;
SeqStack<SElemType> st;
do
{
if (Pass(maze, curpos))
{
FootPrint(maze, curpos);
SElemType e = { curstep,curpos,1 };
st.Push(e);
if (curpos.row == end.row && curpos.col == end.col)
{
return;
}
curpos = NextPos(curpos, 1);
curstep += 1;
}
else
{
if (!st.Is_Empty())
{
SElemType e = st.GetTop();
st.Pop();
while (e.di == 4 && !st.Is_Empty())
{
MarkPrint(maze, e.seat);
e = st.GetTop();
st.Pop();
}
if (e.di < 4)
{
e.di += 1;
st.Push(e);
curpos = NextPos(e.seat, e.di);
}
}
}
} while (!st.Is_Empty());
}
int main()
{
MazeType maze = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,0,0,1,1,0,1},
{1,0,1,1,1,1,1,1,0,1},
{1,0,1,1,0,0,0,0,0,1},
{1,0,1,1,1,1,0,1,1,1},
{1,0,0,0,0,0,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,0,1,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1},
};
Print_Maze(maze);
PosType begin = { 1,1 }, end = { 8,8 };
PathMaze(maze, begin, end);
Print_Maze(maze);
}
2021-07-13 课堂笔记
最新推荐文章于 2021-10-07 15:51:14 发布
本文介绍了如何使用C++编写一个路径搜索算法,通过`MyStack`数据结构在给定的迷宫中从起点到终点寻找路径。通过`Pass`、`FootPrint`和`MarkPrint`函数实现路径遍历和标记,最终输出完整的迷宫路径。
摘要由CSDN通过智能技术生成