地下迷宫-------上下左右移动深度递归

版权声明:转载请注明出处即可 https://blog.csdn.net/qq_35170212/article/details/81460524

题目描述:
小青蛙有一天不小心落入了一个地下迷宫,小青蛙希望用自己仅剩的体力值P跳出这个地下迷宫。为了让问题简单,假设这是一个n*m的格子迷宫,迷宫每个位置为0或者1,0代表这个位置有障碍物,小青蛙达到不了这个位置;1代表小青蛙可以达到的位置。小青蛙初始在(0,0)位置,地下迷宫的出口在(0,m-1)(保证这两个位置都是1,并且保证一定有起点到终点可达的路径),小青蛙在迷宫中水平移动一个单位距离需要消耗1点体力值,向上爬一个单位距离需要消耗3个单位的体力值,向下移动不消耗体力值,当小青蛙的体力值等于0的时候还没有到达出口,小青蛙将无法逃离迷宫。现在需要你帮助小青蛙计算出能否用仅剩的体力值跳出迷宫(即达到(0,m-1)位置)。
输入描述:
输入包括n+1行:
第一行为三个整数n,m(3 <= m,n <= 10),P(1 <= P <= 100)
接下来的n行:
每行m个0或者1,以空格分隔
输出描述:
如果能逃离迷宫,则输出一行体力消耗最小的路径,输出格式见样例所示;如果不能逃离迷宫,则输出”Can not escape!”。 测试数据保证答案唯一
输入:
4 4 10 1 0 0 1 1 1 0 1 0 1 1 1 0 0 1 1
输出:
[0,0],[1,0],[1,1],[2,1],[2,2],[2,3],[1,3],[0,3]

手撕:

#include<iostream>
#include<vector>
using namespace std;

int cost[]={3,1,0,1};//移动消耗
vector<vector<int>> res;//输出
int minCost=2147483647;//最小消耗

static void mydfs(vector<vector<int>>&mp,vector<vector<int>>&path,int p,int x,int y,int cur){
    if(x==0&&y==mp[0].size()-1&&cur<=p){
        if(minCost>cur){
            minCost=cur;
            res=path;
            vector<int>tvr;
            tvr.push_back(x);
            tvr.push_back(y);
            res.push_back(tvr);
        }
    }else{
        int row=mp.size();
        int col=mp[0].size();
        if(x>=0&&x<row&&y>=0&&y<col&&mp[x][y]==1&&cur<=p){
            for(int i=0;i<4;++i){
                mp[x][y]=0;
                vector<int>tvr;
                tvr.push_back(x);
                tvr.push_back(y);
                path.push_back(tvr);
                int nextx=x+abs(i-2)-1;
                int nexty=y+abs(i-1)-1;
                mydfs(mp,path,p,nextx,nexty,cur+cost[i]);
                path.pop_back();
                mp[x][y]=1;
            }
        }
    }
}

测试:

int main(){
    int n=0;
    int m=0;
    int p=0;
    while(cin>>n>>m>>p){
        vector<vector<int>>mp(n,vector<int>(m));
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                cin>>mp[i][j];
            }
        }
        vector<vector<int>>cur;
        mydfs(mp,cur,p,0,0,0);
        if(res.size()){
            for(int i=0;i<res.size();++i){
                cout<<"["<<res[i][0]<<","<<res[i][1]<<"]";
                if(i!=res.size()-1)
                    cout<<",";
            }
            cout<<endl;
        }else{
            cout<<"Can not escape!";
        }
    }
}

题目来源:
https://www.nowcoder.com/practice/571cfbe764824f03b5c0bfd2eb0a8ddf?tpId=85&tqId=29860&rp=2&ru=/ta/2017test&qru=/ta/2017test/question-ranking

猜你喜欢

转载自blog.csdn.net/qq_35170212/article/details/81460524