求最短通路值

25 篇文章 0 订阅
2 篇文章 0 订阅

https://www.nowcoder.com/practice/b83cfe486b494a398609d18b94fb04d3tpId=101&tqId=33106&tPage=1&rp=1&ru=/ta/programmer-code-interview-guide&qru=/ta/programmer-code-interview-guide/question-ranking

题目描述

用一个整形矩阵matrix表示一个网格,1代表有路,0代表无路,每一个位置只要不越界,都有上下左右四个方向,求从最左上角到右下角的最短通路值

例如,matrix为:

1 0 1 1 1

1 0 1 0 1

1 1 1 0 1

0 0 0 0 1

通路只有一条,由12个1构成,所以返回12

[要求]

时间复杂度为O(nm),空间复杂度为O(nm)

 

输入描述:

第一行两个整数N,M表示矩形的长宽
接下来N行,每行一个长度为M的字符串表示矩形

输出描述:

输出一个整数表示最小步数
若从(1, 1)无法到达(n, m)请输出-1

示例1

输入

4 5
10111
10101
11101
00001

输出

12

示例2

输入

4 5
11011
11111
11111
00001

输出

8

备注:

1⩽N,M⩽1000

保证matrix i,j​=0/1,matrix 1,1​=1,matrix n,m​=1 (既保证数值有效,起始点和终止点有效)

//利用BFS求解最短路径
#include<bits/stdc++.h>
using namespace std;
bool isValid(const int& x,const int& y,const int& n,const int& m){
    if((x>=0 && x<n) && (y>=0 && y<m)){
        return true;
    }
    return false;
}
int main(){
    int n,m;
    cin>>n>>m;
    string s;
    vector<vector<int>> matrix(n,vector<int>(m,0));
    for(int i=0;i<n;i++){
        cin>>s;
        for(int j=0;j<m;j++){
           matrix[i][j]=s[j]-'0';
        }
    }
    vector<vector<int>> dist(n,vector<int>(m,0));
    dist[0][0]=1;
    queue<pair<int,int>> q;
    q.push({0,0});
    int d[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
    while(!q.empty()){
        //pair<int,int> a = q.front();
        int x=q.front().first;
        int y=q.front().second;
        q.pop();
        for(int k=0;k<4;k++){
            int newx=x+d[k][0];
            int newy=y+d[k][1];
            //合法能走且没走过,往下走
            if(isValid(newx,newy,n,m) && matrix[newx][newy]!=0 && dist[newx][newy]==0){
                dist[newx][newy]=dist[x][y]+1;
                q.push({newx,newy});
            }
        }
    }
    if(dist[n-1][m-1]){
        cout<<dist[n-1][m-1]<<endl;
    }else{
        cout<<-1<<endl;
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值