迷宫问题

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<Postion> &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;
}
};
stack<Position> _path;
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<Position> &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();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值