代码如下:
#include <iostream>
#include <cstdio>
#include <stack>
#include <cstring>
#include <malloc.h>
#include <queue>
#include <windows.h>
using namespace std;
const int maxn = 4;
typedef int DataType;
typedef struct TreeNode{
struct TreeNode *tou;
DataType biao;
DataType x,y;
struct TreeNode *BU[4];
}TreeNode;
typedef struct TreeNode *BiTree;
int qipan[maxn][maxn];
int x0,y0,x1,y1,X,Y;
int dx[]={0,1,0,-1};
int dy[]={-1,0,1,0};
void shuru(int qipan[maxn][maxn])
{
printf("请输入地图:\n");
for(int i=0;i<maxn;i++)
for(int j=0;j<maxn;j++)
scanf("%d",&qipan[i][j]);
}
void shucu(int qipan[maxn][maxn])
{
for(int i=0;i<maxn;i++)
{
for(int j=0;j<maxn;j++)
{
printf("%d ",qipan[i][j]);
}
printf("\n");
}
}
void chusi()
{
printf("请输入初始坐标:");
scanf("%d %d",&x0,&y0);
printf("请输入目标坐标:");
scanf("%d %d",&x1,&y1);
}
BiTree jiansu()
{
BiTree root = (TreeNode*)malloc(sizeof(TreeNode));
root->biao=1;
root->x=x0;
root->y=y0;
for(int i=0;i<4;i++)
{root->BU[i]=(TreeNode*)malloc(sizeof(TreeNode));root->BU[i]->biao=0;qipan[y0][x0]=1;root->BU[i]->tou=root;}
return root;
}
void chuangjian(BiTree Tree)
{
for(int i=0;i<4;i++)
{
X=Tree->x+dx[i];
Y=Tree->y+dy[i];
if(X>=0&&X<maxn&&Y>=0&&Y<maxn&&qipan[Y][X]==0){Tree->BU[i]=(TreeNode*)malloc(sizeof(TreeNode));Tree->BU[i]->x=X;Tree->BU[i]->y=Y;Tree->BU[i]->biao=1;qipan[Y][X]=1;Tree->BU[i]->tou=Tree;}
else{Tree->BU[i]=(TreeNode*)malloc(sizeof(TreeNode));Tree->BU[i]->biao=0;Tree->BU[i]->biao=0;}
}
}
BiTree LevelOrder(BiTree root)
{
int N=0,k=0;
queue<BiTree> q;
BiTree front;
if (root == NULL)return NULL;
q.push(root);
if(root->x==x1&&root->y==y1){return NULL;}
while (!q.empty())
{
front = q.front();
q.pop();
printf("%d %d\n",front->x,front->y);
if(front->x==x1&&front->y==y1){return front;}
chuangjian(front);
for(int i=0;i<4;i++)
{
//Sleep(10);
if (front->BU[i]->biao)
q.push(front->BU[i]);
}
}
}
int main()
{
int n=0;
BiTree lushu;
chusi();
memset(qipan, 0, sizeof(qipan));
shuru(qipan);
BiTree root=jiansu();
lushu=LevelOrder(root);
while(lushu)
{
if(lushu==root)break;
lushu=lushu->tou;
n++;
}
printf("最短步数为%d\n",n);
return 0;
}
输出结果(例):
请输入初始坐标:0 0
请输入目标坐标:3 3
0 1 1 1
0 0 1 1
1 0 0 1
1 1 0 0
最短步数为6
本文详细介绍了一种基于树结构的迷宫寻路算法,通过使用C++编程语言,实现了从起点到终点的最短路径搜索。算法首先构建了一个树形数据结构,然后通过层级遍历的方式找到目标坐标,最后计算并输出了从起点到终点的最短步数。

321

被折叠的 条评论
为什么被折叠?



