谁改变了我的矩阵?神秘的虫子

时间:2013-09-06 21:41:48

标签: c++ arrays vector

过去两个小时我一直被困在这个小虫子身上,现在我很绝望。任何帮助都非常感谢!

该算法用于在两个序列之间制作Longest Common Subsequence的矩阵问题。矩阵用作Dynamic Programming方法中的参考表。粘贴相关代码

#include <vector>
#include <cstdio>
#include <math.h>

using namespace std;
int main()
{
  vector<int> A, B;
  A.push_back(0);
  A.push_back(15);
  A.push_back(20);
  B.push_back(0);
  B.push_back(20);
  B.push_back(15);

  int a = 2;
  int b = 2;
  int matrix[a][b];
  memset(matrix, 0, sizeof(int)*a*b);

  for (int i = 0; i <= a; ++i)
  {
    for (int j = 0; j <= b; ++j)
    {
      if (i == 0 || j == 0)
      {
        matrix[i][j] = 0;
      } else 
      {
        if (A[i] == B[j])
        {
          matrix[i][j] = matrix[i - 1][j - 1] + 1;
          printf("matrix at row %i column %i: %i\n", i, j, matrix[i][j]);
        } else
        {
          matrix[i][j] = max(matrix[i - 1][j], matrix[i][j - 1]);
        }
      }
    }
  }
  printf("matrix at row 1 column 2: %i\n", matrix[1][2]);
  printf("matrix at row 2 column 1: %i\n", matrix[2][1]);
}

如果我使用

编译并运行它
g++ -Wall soquestion1.cpp -o soquestion1
./soquestion1

我得到了

matrix at row 1 column 2: 1
matrix at row 2 column 1: 1
matrix at row 1 column 2: 0     #WTHHHHHH, who changed my matrix!?
matrix at row 2 column 1: 1

感谢您阅读那么远。

2 个答案:

答案 0 :(得分:2)

for (int i = 0; i <= a; ++i)
  {
    for (int j = 0; j <= b; ++j)
    {

这是你的问题。你走出界限,导致......“某事”。

设为<a<b,你应该没问题。你也正在访问矩阵本身,并没有真正阅读那里的内容。 你有没有检查结果应该是什么?

  printf("matrix at row 1 column 2: %i\n", matrix[1][2]);
  printf("matrix at row 2 column 1: %i\n", matrix[2][1]);

应该是matrix[0][1]matrix[1][0]

注意:预期结果应为0和0

答案 1 :(得分:1)

你的代码有点混乱。我清理了一些。

#include <algorithm>
#include <cstdio>

int main()
{
  int A[] = { 0, 15, 20 };
  int B[] = { 0, 20, 15 };

  const size_t MatrixDim = 3;
  int matrix[MatrixDim][MatrixDim] = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }; 
  // or memset(matrix, 0, sizeof(matrix));

  // only operate on dimensions 1 and 2, leave 0,j and i,0 elements as 0. 
  for (size_t i = 1; i < MatrixDim; ++i)
  {
    for (size_t j = 1; j < MatrixDim; ++j)
    {
      if (A[i] == B[j])
      {
        matrix[i][j] = matrix[i - 1][j - 1] + 1;
        printf("a. matrix at row %i column %i: %i\n", i, j, matrix[i][j]);
      }
      else
      {
        matrix[i][j] = std::max(matrix[i - 1][j], matrix[i][j - 1]);
        printf("b. matrix at row %i column %i: %i\n", i, j, matrix[i][j]);
      }
    }
  }

  for (size_t i = 0; i < MatrixDim; ++i) {
    for (size_t j = 0; j < MatrixDim; ++j) {
      printf("%02d ", matrix[i][j]);
    }
    printf("\n");
  }
}

现场演示:http://ideone.com/vGk4oB

输出:

a. matrix at row 1 column 2: 1
a. matrix at row 2 column 1: 1
b. matrix at row 2 column 2: 1
00 00 00 
00 00 01 
00 01 01