#include<stdio.h>
#include<iostream>
using namespace std;
int mg[10][10]
{
{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},
};
//入口(1,1),出口(8,8)
typedef struct
{ int x;
int y;
int pre;
}gezi;
typedef struct
{ gezi way[200];
int front,rear;
}Path;
void print(Path p,int pos)
{ int end=pos;
int j,k=pos;
do
{
j=k;
k=p.way[k].pre;
p.way[j].pre=-1;
}while(k!=0);//容易出错,
for(int i=0;i<=end;i++)
{
if(p.way[i].pre==-1)
printf("(%d,%d)\n",p.way[i].x,p.way[i].y);
}
}
void SearchWay(int xi,int yi,int xe,int ye){
Path p;
p.front=p.rear=0;
p.way[0].x=xi; p.way[0].y=yi; p.way[0].pre=-1;mg[1][1]=-1;//起始位置
int tx,ty;
p.front=-1;
int di;
while(p.front!=p.rear)
{ p.front++;
tx=p.way[p.front].x; ty=p.way[p.front].y;
if(p.way[p.front].x==8&&p.way[p.front].y==8)
{ printf("///\n");
//printf("p.front=%d",p.front);
print(p,p.front);//输出整体路径
printf("...............\n");
//for(int i=0;i<=p.front;i++)
// printf("(%d,%d)\n",p.way[i].x,p.way[i].y);
return;
}
//进行路径搜索
if(mg[tx-1][ty]==0)
{ mg[tx-1][ty]=-1;
p.rear++;
p.way[p.rear].x=tx-1; p.way[p.rear].y=ty;
p.way[p.rear].pre=p.front;
}
if(mg[tx+1][ty]==0)
{ mg[tx+1][ty]=-1;
p.rear++;
p.way[p.rear].x=tx+1; p.way[p.rear].y=ty;
p.way[p.rear].pre=p.front;
}
if(mg[tx][ty+1]==0)
{ mg[tx][ty+1]=-1;
p.rear++;
p.way[p.rear].x=tx; p.way[p.rear].y=ty+1;
p.way[p.rear].pre=p.front;
}
if(mg[tx][ty-1]==0)
{ mg[tx][ty-1]=-1;
p.rear++;
p.way[p.rear].x=tx; p.way[p.rear].y=ty-1;
p.way[p.rear].pre=p.front;
}
/*for(di=0;di<4;di++)
{
switch(di)
{
case 0:tx=p.way[p.front].x-1;ty=p.way[p.front].y;break;
case 1:tx=p.way[p.front].x+1;ty=p.way[p.front].y;break;
case 2:tx=p.way[p.front].x;ty=p.way[p.front].y+1;break;
case 3:tx=p.way[p.front].x;ty=p.way[p.front].y-1;break;
}
if(mg[tx][ty]==0)
{
p.rear++;
p.way[p.rear].x=tx; p.way[p.rear].y=ty;
p.way[p.rear].pre=p.front;
mg[tx][ty]=-1;
}
}*/
}
}
int main(){
SearchWay(1,1,8,8);
}
在实现过程中遇到的问题有:
1、忘记在迷宫位置入队的时候,将mg[i][j]置为-1,否则将会回溯,导致得不到解;
2、在反向输出迷宫路径的时候,要判断数组下标,元素的pre,和-1之间的关系。正确思路是:
类似链表的free操作,标记下一个元素,释放当前元素,将当前元素赋给下一个元素,如此循环
学习到的东西有:利用swtich操作,简洁代码的重复性。
只需要利用case列出可能取到的路径,再统一用if判断语句进行入队列。