开发者

C++ Recursively find shortest path in horizontal cylinder.(Problem with recursion)

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;
}
/开发者_StackOverflow中文版/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.

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;
}


Take the first recursive call to rec_path() (that you have commented out). Once the call returns, c has a value of 6. Then in the second call to rec_path() the 6 is incremented to 7 before the call (that is, ++c). Now c is out of range which causes the fault.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜