[编程题]地下迷宫

  题目位置:https://www.nowcoder.com//questionTerminal/571cfbe764824f03b5c0bfd2eb0a8ddf

题目解答的代码如下:

#include<iostream>
#include<stack>
using namespace std;
class position{
    public:
    int row;
    int col;
    position(){}
    position(int rr,int cc):row(rr),col(cc){}
};
stack<position> path;
stack<position> minpath;
bool isPass(int **maze,int n,int m,position thispos){
    if(thispos.row>=0&&thispos.row<n&&thispos.col>=0&&thispos.col<m
      &&maze[thispos.row][thispos.col]==1)
        return true;
    else
        return false;
}
void PrintPath(stack<position> &output){
    stack<position> temp;
    while(!output.empty()){
        temp.push(output.top());
        output.pop();
    }
    while(temp.size()>1){
        cout<<'['<<temp.top().row<<','<<temp.top().col<<']'<<',';
        temp.pop();
    }
    cout<<'['<<temp.top().row<<','<<temp.top().col<<']';
    temp.pop();
}
void GetMazePath(int **maze,int n,int m,position cur,int p){
    path.push(cur);
    if(cur.row==0&&cur.col==m-1){
        if(p>=0&&minpath.empty()||p>=0&&(path.size()<minpath.size())){
            minpath=path;
        }
    }
    position next;
    maze[cur.row][cur.col]=2;//标记已经走过
    next=cur;
    next.row-=1;
    if(isPass(maze,n,m,next))
        GetMazePath(maze,n,m,next,p-3);
    next=cur;
    next.row+=1;
    if(isPass(maze,n,m,next))
        GetMazePath(maze,n,m,next,p);
    next=cur;
    next.col-=1;
    if(isPass(maze,n,m,next))
        GetMazePath(maze,n,m,next,p-1);
    next=cur;
    next.col+=1;
    if(isPass(maze,n,m,next))
        GetMazePath(maze,n,m,next,p-1);
    
    maze[cur.row][cur.col]=1;
    path.pop();
}
int main(){
    int n=0,m=0,p=0;
    while(cin>>n>>m>>p){
        int **maze=new int*[n];
        for(int i=0;i<n;i++){
            maze[i]=new int [m];
        }
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>maze[i][j];
            }
        }
        position entry(0,0);
        GetMazePath(maze,n,m,entry,p);
        if(!minpath.empty()){
            PrintPath(minpath);
        }
        else
            cout<<"Can not escape!";
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值