struct Postion
{
int _X, _Y;
Postion(){}
Postion(int X, int Y)
: _X(X), _Y(Y){}
};
bool isCanGo(const int prePosValue,
const int posX,
const int posY)
{
if ( posX < 0 || posX > 9 // 越界
|| posY < 0 || posY > 9
|| maze[posX][posY] == -1) // 墙
{
return false;
}
if (maze[posX][posY] == 0) // 未走过
return true;
else // 更近的路径
return (prePosValue + 1) < maze[posX][posY];
}
void shortestPath(stack
&path,
const Postion &start,
const Postion &end)
{
if ( start._X == end._X
&& start._Y == end._Y)
{
if (path.size() < path__.size() || path__.empty()) // 更短的路径
path__ = path;
return;
}
for (int i = 0; i < 4; i++)
{
int nNextPos_X = start._X + offset[i]._X;
int nNextPos_Y = start._Y + offset[i]._Y;
if (isCanGo(maze[start._X][start._Y], nNextPos_X, nNextPos_Y))
{
maze[nNextPos_X][nNextPos_Y] = maze[start._X][start._Y] + 1;
path.push(Postion(nNextPos_X, nNextPos_Y));
shortestPath(path, Postion(nNextPos_X, nNextPos_Y), end);
path.pop();
}
}
}
struct Position{
int _X;
int _Y;
Position(int x, int y){
_X = x;
_Y = y;
}
};
bool InsCanGo(int prevalue , int posx , int posy , int *maze){
if(posx < 0 || posy > 9 || maze[posx][posy] == -1)
return false;
if(maze[posx][posy] == 0 )
return true;
else{
return (prevalue + 1) < maze[posx][posy];
}
}
int offset[0]._X = 1 , offset[0]._Y = 0;
int offset[1]._X = -1 , offset[1]._Y = 0;
int offset[2]._X = 0 , offset[2]._Y = 1;
int offset[3]._X = 0 , offset[3]._Y = -1;
void ShortPath(stack
&path , Position &start , Position &end){
if(start._X == end._X && start._Y == end._Y){
if(path.size() < _path.size())
_path = path;
return;
}
for (int i = 0 ; i < 4 ; i ++){
int n_nextposx = start._X + offset[i]._X;
int n_nextposy = start._Y + offset[i]._Y;
if(isCanGo(maze[start._X][start._Y],n_nextposx,n_nextposy)){
maze[n_nextposx][n_nextposy] = maze[start._X][start._Y] + 1;
path.push(Position(n_nextposx,n_nextposy));
ShortPath(path,Position(n_nextposx,n_nextposy),end);
path.pop();
}
}
}