c++ - 为什么我计算邻接矩阵的算法在只应使用 0 和 1 时输出 '8'?

标签 c++

我现在正在做一个图形程序,但还没有完成,这是关于我之前的问题(About matrix of edge in graph using c++),这是一些示例程序

#include <iostream>

using namespace std;

int main()
{
   int n, m = 0, i, j, k, l;
   cout << "How many vertex in graph : ";
   cin >> n;
   cout << endl << endl;

   int A[n][n], A1[n][n];

   for(i = 1; i <= n; i++)
      for(j = 1; j <= n; j++)
      {
         cout << "A[" << i << "][" << j << "] = ";
         cin >> A[i][j];
         if (A[i][j] == 1)
            m++;
      }

   for(i = 1; i <= n; i++)
      for(j = 1; j <= n; j++)
         A1[i][j] = A[i][j];

   m = m / 2;
   int B[m][m];
   cout << endl << "Adjacency Matrix A : " << endl;
   /* Problem
   for(i = 1; i <= n; i++)
      for(j = 1; j <= n; j++)
      {
        cout << A[i][j] << " ";
        if(j == n)
            cout << endl;
      }
   */
   cout << endl;

   /* Problem's maker
   for(i = 1; i <= n; i++) 
      for(j = 1; j <= n; j++)
        if(A1[i][j] == 1)
        {
            for(k = 1; k <= n; k++)
                for(l = 1; l <= n; l++)
                    if(A1[k][l] == 1)
                    {
                        if(k == i && l == j)
                            B[i][j] == 0;
                        else if (k == j  && l == i)
                            A1[k][l] == 0;
                        else if(k == i || k == j || l == i || l == j)
                            B[i][j] == 1;
                        else
                            B[i][j] == 0;
                    }
        }*/

并且,如果我依次输入 0,1,1,1,0,0,1,0,0。我绝对确定输出是:

0 1 1
1 0 0
1 0 0

但它给出了:

0 1 1
1 0 0
1 0 8

这部分我不知道,我认为这是由 /*Problem maker 引起的。我知道我不太了解 C++,但是对于 /*Problem 部分我确信我做对了。即使 /*Problem maker 部分因其算法或其他原因而出错,它也没有与 /*Problem 部分相关联,对吧?

如果我删除了 /*Problem maker 部分,输出会很好。

最佳答案

int A[n][n] ;

A 只能遍历从 i = 0 到 n-1 开始的所有行和从 j = 0 到 n-1< 开始的所有列

访问 A[n][n] 会调用未定义的行为

当然你可以通过不同的方法来解决这个问题

关于c++ - 为什么我计算邻接矩阵的算法在只应使用 0 和 1 时输出 '8'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22595735/

相关文章:

c++ - FOR 循环中的条件

c++ - Linux 上只有一个线程可能导致死锁或卡住程序?

c++ - SDL访问SDL_Surface的像素数据

c++ - 在控制台中获取是/否总是失败

c++ - 使用接口(interface)会减慢程序速度吗?

c++ - Qt qreal计算错误

c++ - 命名空间和 undefined reference

c++ - 解决问题后对函数的 undefined reference

c++ - 绑定(bind)对象未在 VS2015 上编译

c++ - 在 Mac 终端编译 OpenGL 程序