迷宫问题求解算法.docx
《迷宫问题求解算法.docx》由会员分享,可在线阅读,更多相关《迷宫问题求解算法.docx(19页珍藏版)》请在冰豆网上搜索。
迷宫问题求解算法
思想:
采用试探法,从某一点出发,先向右探测,如果不同;就向下探测;还是不通就向左探测亦然不通就返回前一个结点。
第一次源代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
usingnamespacestd;
#defineMAX100
classCoordinate
{
private:
introw;
intcol;
public:
Coordinate(intr,intc)
{
row=r;
col=c;
}
~Coordinate(){}
voidSet_row(intr){row=r;}
voidSet_col(intc){col=c;}
intGet_row(){returnrow;}
intGet_col(){returncol;}
};
classMazenode
{
private:
introw,col;
intdir,ord;
public:
Mazenode()
{
row=-1;
col=-1;
ord=-1;
dir=-1;
}
voidSet_ord(into){ord=o;}
voidSet_row(intr){row=r;}
voidSet_col(intc){col=c;}
voidSet_dir(intd){dir=d;}
intGet_ord(){returnord;}
intGet_row(){returnrow;}
intGet_col(){returncol;}
intGet_dir(){returndir;}
};
classMaze
{
private:
introw;
intcol;
char**grid;
public:
Maze(intr,intc,multimapgg)
{
row=r+2;
col=c+2;
intrr,cc;
multimap:
:
iteratorpos;
//initthemaze
grid=newchar*[r+2];
for(inti=0;igrid[i]=newchar[c+2];
for(inti=0;ifor(intj=0;jgrid[i][j]='0';
//settheobscal
for(inti=0;i{
grid[0][i]='1';
grid[r+1][i]='1';
}
for(inti=0;i{
grid[i][0]='1';
grid[i][c+1]='1';
}
for(pos=gg.begin();pos!
=gg.end();++pos)
{
rr=pos->first;
cc=pos->second;
grid[rr][cc]='1';
}
}
~Maze()
{
for(inti=0;i
delete[]grid[i];
delete[]grid;
}
intGet_row(){returnrow;}
intGet_col(){returncol;}
char**Get_grid(){returngrid;}
voidPrintmaze()
{
cout<<"Themazeinformationisfollow:
"<for(inti=0;i{
for(intj=0;j
cout<cout<}
}
};
//getthenextcoordinate
CoordinateNextcoord(Coordinatepos,intk)
{
inttemp=-1;
switch(k)
{
case1:
//right
temp=pos.Get_col()+1;
pos.Set_col(temp);
break;
case2:
//down
temp=pos.Get_row()+1;
pos.Set_row(temp);
break;
case3:
//left
temp=pos.Get_col()-1;
pos.Set_col(temp);
break;
case4:
//up
temp=pos.Get_row()-1;
pos.Set_row(temp);
break;
default:
cout<<"it'swrong!
"<exit(0);
}
returnpos;
}
intPassMaze(Maze*mm,Coordinatestart,Coordinateend)
{
vectorpath;
vector:
:
iteratorpos;
intcurstep=1,row_c,col_c,tt;
Mazenodee;
row_c=start.Get_row();
col_c=start.Get_col();
Coordinatetemp(row_c,col_c);
//mm->Printmaze();
int**map;
row_c=mm->Get_row();
col_c=mm->Get_col();
map=newint*[row_c];
for(inti=0;imap[i]=newint[col_c];
cout<<"themapis:
"<for(inti=0;i{
for(intj=0;j{
if(mm->Get_grid()[i][j]=='1')
map[i][j]=1;
else
map[i][j]=0;
cout<
|