Mohit Singh
Mohit Singh

Reputation: 1

Segmentation Fault in the following code

I am beginner in coding and have basic knowledge of data structres and algorithms

I am writing a code to find the maximum connected area in matrix having atmost two different integers such that we can move from any cell to any other cell in this set by only moving between side-adjacent cells from the set. for example matrix like

1 1 2 3 1 3 1 2 5 2 5 2 1 5 6 1 3 1 2 1

answer will be 10 as

1 1 2 . . . 1 2 . . . 2 1 . . . . 1 2 1

will be the max connected area.I have written the code for this but i am getting segmentation fault in my code

 #include <bits/stdc++.h>
using namespace std;
long long int mat[2000][2000];
int dp[2000][2000];
long long int temp[2000][2000];
int findLongestFromACell(int i, int j,int n,int m)
{
    if (i<0 || i>=n || j<0 || j>=m)
        return 0;
    if (dp[i][j] != -1)
        return dp[i][j];
    if (j<m-1 && ((temp[i][j]) == temp[i][j+1]))
      return dp[i][j] = 1 + findLongestFromACell(i,j+1,n,m);

    if (j>0 && (temp[i][j]  == temp[i][j-1]))
      return dp[i][j] = 1 + findLongestFromACell(i,j-1,n,m);

    if (i>0 && (temp[i][j]  == temp[i-1][j]))
      return dp[i][j] = 1 + findLongestFromACell(i-1,j,n,m);

    if (i<n-1 && (temp[i][j]  == temp[i+1][j]))
      return dp[i][j] = 1 + findLongestFromACell(i+1,j,n,m);
    return dp[i][j] = 1;
}

int finLongestOverAll(int n,int m,long long int p,long long int q)
{
    for(int l=0;l<n;l++)
        for(int k=0;k<m;k++)
            {
                temp[l][k] = mat[l][k];
                dp[l][k] = -1;
                if (mat[l][k]==q)
                    temp[l][k] = p;
            }
    int result = 1;
    for (int i=0; i<n; i++)
    {
      for (int j=0; j<m; j++)
      {
          if (dp[i][j] == -1)
             findLongestFromACell(i, j,n,m);
          result = max(result, dp[i][j]);
      }
     }     
     return result;
}
int main() 
{
    int n,m;
    vector <int> a;
    cin>>n>>m;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
            cin>>mat[i][j];
            if (find(a.begin(),a.end(),mat[i][j]) == a.end())
                a.push_back(mat[i][j]);
        }
        int l =1;
    for(int i =0;i<a.size();i++)
        for(int j=i+1;j<a.size();j++)
        {
            int m = finLongestOverAll(n,m,a[i],a[j]);
            if (m>l)
                l=m;
        }
    cout<<l;
    return 0;
}

is this due to size overflow of 2d arrays or some thing else. I looked it over over again but i cant find the mistake

Thanks in advance

Upvotes: 0

Views: 50

Answers (1)

knandy
knandy

Reputation: 11

There may be cases where your recursive function keeps recursing infinitely. For example, let's say temp (I,J) = temp (I,J+1). Your recursive function hops between these two states infinitely, leading to a segmentation fault due to stack overflow.

Upvotes: 1

Related Questions