0

I am trying to find the all-pairs shortest paths matrix for a 5x5 matrix, but the output is not showing the right answer.

Here is the initial matrix and my output:

enter image description here

Here is the actual solution though:

[0, 2, 3, 1, 4, 

6, 0, 3, 2, 5

10, 12, 0, 4, 7,

6, 8, 2, 0, 3,

3, 5, 6, 4, 0]

As you can see, it reads the initial matrix correctly, but somewhere in the code, the math isn't being applied correctly, or something is messing up.

Below is my code, can you find my mistakes?

int matrixFloyd(int *C, int n, int *A, string* s)
{

  int i,j,k;

  for (i=0; i<n; i++)
  {
    for (j=0; j<n; j++)
    {
      if ( *(C+i*n+j) == -1)
      {
        *(A+i*n+j) = 999999999;
      }
      else
      {
        *(A+i*n+j) = 1;
        char sz[3]="";
        sprintf(sz,"%d",j+1);
        s[i*n+j]=sz;
      }
    }
  }

  for (i=0; i<n; i++)
  {
    *(A+i*n+i) = 0;
  }

  for (k=0; k<n; k++)
  {
    for (i=0; i<n; i++)
    {
      for (j=0; j<n; j++)
      {
        if ( *(A+i*n+k) + *(A+k*n+j) < *(A+i*n+j) )

          // A[i][j] = A[i][k] + A[k][j];
          *(A+i*n+j) = *(A+i*n+k)+ *(A+k*n+j);
      }
    }
  }

  return 0;
}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162

1 Answers1

2

You're ignoring the original C values:

*(A+i*n+j) = 1;

Should be

*(A+i*n+j) = *(C+i*n+j);
Pablo
  • 8,644
  • 2
  • 39
  • 29
  • Ok, so one last issue I have with this code: *(A+i*n+j) = 999999999; Clearly, 99999999 isn't really infinite, but when I replace "99999999" with "(unsigned int)(-1)", it breaks the output. I've also tried including and using INT_MAX and LONG_LONG_MAX, but neither of these works either. Is there a way to fix this issue? –  Apr 18 '12 at 20:01
  • You can't use `INT_MAX` because then your addition `*(A+i*n+k) + *(A+k*n+j)` overflows and ends up being smaller than `*(A+i*n+j)`. Same applies for `LONG_LONG_MAX` – Pablo Apr 18 '12 at 20:04
  • Ah, I see. Is there any way to address the issue? If not, it's no big deal! –  Apr 18 '12 at 20:05
  • Don't use `INT_MAX` ? A "large enough" value should suffice. If you really want to use it, cast the values to a wider data type before adding: `(long long)*(A+i*n+k) + ...` – Pablo Apr 18 '12 at 20:19