【问题标题】:C++ Recursively find shortest path in horizontal cylinder.(Problem with recursion)C ++递归找到水平圆柱体中的最短路径。(递归问题)
【发布时间】:2011-04-16 03:36:54
【问题描述】:

这个程序应该返回二维数组中从左到右的最短路径的权重(它也可以越过顶部和底部,所以它就像一个水平圆柱体)。(这是一个完整的@987654321 @) 我试图通过首先向上,然后向右,最后在数组中向下递归检查。 通过运行这个程序,如果我取消注释行的右方向和底部方向,我会得到“分段错误”。 如果有人能告诉我我在递归函数中做错了什么。提前致谢!

#include<iostream>
using namespace std;

int rec_path(int matrix[5][6], int r, int c){
static int sum = 0;
static int weight = -1;
    if (r == -1) 
    r = 4;

if (r == 5) 
    r = 0;

if (c == 6) {
    return weight;
    sum = 0;
}
//calculate sum 
sum += matrix[r][c];    
//check the up direction
rec_path(matrix, --r, ++c);
//check the right direction
//  rec_path(matrix, r, ++c);
//check the bottom direction
//  rec_path(matrix, ++r, ++c);
if (weight == -1) 
    weight = sum;
if ( weight < sum) {
    weight = sum;
}
}


int main(){
const int row = 5;
const int col = 6;
int matrix[row][col] = {{3,4,2,1,8,6},
                        {6,1,8,2,7,4},
                        {5,9,3,9,9,5},
                        {8,4,1,3,2,6},
                        {3,7,2,8,6,4}
                        };

cout << rec_path(matrix,0,0) << endl;
return 0;
}

【问题讨论】:

    标签: c++ recursion path shortest


    【解决方案1】:

    给你。这只会返回路径的成本,找到实际路径只是 对此进行简单修改。

    int rec_path(int matrix[5][6],int r,int c,int cost)
    {
        if(c==6) return cost;
        int ans=2e9;
        static const int dr[]={-1,0,1};
        for(int i=0;i<3;i++)
            ans=min(ans,rec_path(matrix,(5+(r+dr[i])%5)%5,c+1,cost+matrix[r][c]));
        return ans;
    }
    

    【讨论】:

    • 你可以做到(5+r+dr[i])%5
    • 哦,伙计!这太神奇了!!!我现在必须考虑一下您的简单修改是如何工作的=))) 非常感谢!
    • 2e9 是我猜的最大整数?
    • 谢谢。是的..您可以更改 INT_MAX(在 limits.h 中定义)。
    【解决方案2】:

    对 rec_path() 进行第一次递归调用(您已将其注释掉)。一旦调用返回,c 的值为 6。然后在对 rec_path() 的第二次调用中,6 在调用之前递增到 7(即 ++c)。现在 c 超出范围导致错误。

    【讨论】:

    • 是的,我想我必须将 c 的值改回 0,或者只是减少 c.. 谢谢,我会试试的!
    猜你喜欢
    • 2019-03-27
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多