C ++递归地找到水平圆柱体中的最短路径。(递归问题)
|
该程序应该以二维数组的形式返回从左到右的最短路径的权重(它也可以越过顶部和越过底部,因此就像水平圆柱一样)。(这里有一个完整的question_link)
我试图通过首先向上,然后向右,最后向下在数组中进行递归检查。
通过运行该程序,如果我取消注释正确的方向和底部的方向,则会得到“分段错误”。
如果有人可以告诉我递归函数中我在做什么错。提前致谢!
#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;
}
没有找到相关结果
已邀请:
2 个回复
丧泉缝锋
壬驴拿歪竞