yagamilight1994
yagamilight1994

Reputation: 15

Why my algorithm for calculating adjacency matrix outputs '8' when only 0 and 1 should be used?

I'm doing a graph program right now, but it isn't finished yet, it's about my question before (About matrix of edge in graph using c++), and this is some sample program

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

and, if I input sequentially 0,1,1,1,0,0,1,0,0. I absolutely sure the output is :

0 1 1
1 0 0
1 0 0

but it gives :

0 1 1
1 0 0
1 0 8

This part where I have no idea, I think it's cause by /*Problem maker. I know I don't understand C++ well enough, but for /*Problem part I'm sure I get it right. Even though /*Problem maker part is wrong by its algorithms or whatever, it doesn't connected with the /*Problem part right?

If I deleted the /*Problem maker part, the output is well and nice.

Upvotes: 0

Views: 78

Answers (1)

P0W
P0W

Reputation: 47814

In int A[n][n] ;

A can only be traversed for all rows starting from i = 0 to n-1 on all columns starting from j = 0 to n-1

Accessing A[n][n] invokes a undefined behavior

Of course you can fix this by different approachs

Upvotes: 2

Related Questions