This program should return the weight of the shortest path from left to right(it also can go over the top and over the bottom, so it’s like a horizontal cylinder) in two-dimentional array.(here is a full question_link)
I’m trying to check recursively by first going up,then right and finally down in the array.
By running this program I’m getting “Segmentation fault” if I uncomment the lines right direction and bottom direction.
If anyone can tell me what I’m doing wrong in my recursive function. Thanks in advance!
#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;
}
Here you go. This will just return the cost of the path, finding the actual path is just
a simple modification of this.