View Single Post
Old 11-17-2004, 01:58 AM   #1 (permalink)
toast28
Registered User
 
Join Date: Sep 2004
Posts: 21
toast28 is on a distinguished road
Graphs and matrices

OK, so I have an assignment due about graphs. We are to use the floyd warshall algorithum to find the diameter of each graph. I have some code for the algorithum, but I am getting some strange results. Using the graph info below, when I get to 0-7, instead of taking the 8, it finds the -1 part of the equation and skips the if statement. Anyone know what I need to add to avoid mistakes like this?

I know where the mistake is, but not the logical answer to it. I bolded it so you can find it fast. Any help will be appreciated.

Code:
void map::floyd()
{
	//initalize path matrix
	for(int i=0;i<MAX_NODES;i++)
	{
		for(int j=0;j<MAX_NODES;j++)
		{
			if(adj[i][j]!=-1)
				path[i][j] = j;
			else
				path[i][j] = -1;

		}
	}


	//floyd warshall alg
	for(i=0;i<N;i++)
	{
		for(int j=0;j<N;j++)
		{
			for(int k=0;k<N;k++)
			{
				if((adj[i][j] > adj[i][k] + adj[k][j]) && 
					(path[i][k] !=-1 && path[j][k] !=-1) &&
					(adj[i][k] != -1 && adj[k][j] != -1))
				{
					adj[i][j] = adj[i][k] + adj[k][j];
					//adj[j][i] = adj[i][j];
					path[i][j] = path[i][k];
				}
			}
		}
	}

}
Code:
11   13
0    3     -1     -1     -1      12     10     -1     -1     -1     -1
1   -1     -1     -1      2       7      8     -1     -1      1
2    2     -1     -1     -1      -1     -1      8     -1
3   -1     -1     -1     -1      -1      4     -1
4   -1     -1     -1     -1      -1     -1
5    3     -1     -1     -1      -1
6   -1      5     -1     -1
7    5     -1     -1
8   -1     -1
9   -1
10
toast28 is offline   Reply With Quote