【问题标题】:Segmentation Fault in the following code以下代码中的分段错误
【发布时间】:2018-11-19 10:55:20
【问题描述】:

我是编码初学者,对数据结构有基本的了解 和算法

我正在编写一个代码来查找矩阵中的最大连通区域 两个不同的整数,这样我们就可以从集合中的任何单元格移动到该集合中的任何其他单元格,只需在集合中的边相邻单元格之间移动。 例如像

这样的矩阵

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

答案将是 10

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

将是最大连接区域。我已经为此编写了代码,但我的代码中得到了segmentation fault

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

这是由于二维数组的大小溢出还是其他原因。 我又看了一遍,但我找不到错误

提前致谢

【问题讨论】:

  • 如果你想正确学习编程和C++,我建议你阅读get a few good books,了解计算机体系结构(例如了解什么会导致分段错误)和learn how to debug your programs。还有你should never include &lt;bits/stdc++.h&gt;.
  • 您的矩阵每个大约 32MB。我预见到的问题是,使用大 n,m 您可能会溢出用于递归 finLongestXXX 调用的堆栈。
  • 它也为n=3 m=3 提供segmentation fault
  • 你的调试器说什么?段错误何时发生?
  • 我尝试在在线调试器中调试您的程序,似乎即使对于 2x2 矩阵,递归也会永远进行。

标签: c++ error-handling segmentation-fault


【解决方案1】:

在某些情况下,您的递归函数会无限递归。例如,假设 temp (I,J) = temp (I,J+1)。您的递归函数在这两种状态之间无限跳跃,导致由于堆栈溢出而导致分段错误。

【讨论】:

  • ...因为findLongestFromACell(i,j-1,n,m);
猜你喜欢
  • 2015-06-24
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多