该程序应该从左到右返回最短路径的权重(它也可以超过顶部和底部,所以它就像一个水平圆柱体)在二维数组中(这里是一个完整的question_link) 我试图通过首先向上检查,然后右对齐,最后在数组中进行递归检查。 通过运行这个程序,我得到了“分段错误”,如果我取消注释线的正确方向和底部方向。 如果任何人都可以告诉我我在做递归函数时做错了什么。提前致谢!C++递归找到水平圆柱体中的最短路径(递归问题)
#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;
}
你可以让它成为'(5 + r + dr [i])%5'。 – SuperSaiyan 2011-04-16 04:51:14
哦,伙计!这是魔术!我现在必须考虑你的简单修改是如何工作的=)))非常感谢! – Andrey 2011-04-16 13:14:49
2e9是我猜的最大int吗? – Andrey 2011-04-16 13:15:08