I'm working on a Floyd's Algorithm type Java program.
What I have done so far is represent a directed graph in a 2d array, and I am trying to transform that into a 2d array representing the graph's paths of length 2.

I planned for it to fill the adj2[][] array to represent the graph's paths of length 2 which should be:
0 0 2 0 0
2 0 0 2 0
0 2 0 0 2
0 2 2 0 0
0 0 2 0 0
However, when I go to print out the adj2[][] array, it just comes up as containing all zeros.

Any help on why this isn't working would be greatly appreciated!

This is what I have right now:

``````int adj[][] = {{0,1,0,0,0},
{0,0,1,0,0},
{1,0,0,1,0},
{0,1,0,0,1},
{0,1,0,0,0}};

int path = 0;

for (int n = 0; n < adj2.length; n++) {
for (int m = 0; m < adj2.length; m++) {
for (int i = 0; i < adj2.length; i++) {
for (int j = 0; j < adj2.length; j++) {
}
if (path > 0) {
}
}
}
}
for (int a = 0; a < adj2.length; a++) {
for (int b = 0; b < adj2.length; b++) {
}
System.out.println();
}``````

Edited by nola_Coder: n/a

4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by nola_Coder
``````for (int i = 0; i < adj2.length; i++) {
for (int j = 0; j < adj2.length; j++) {
}
}``````

The above always returns 0. If you run the code by hand you will see that the above snippet, never has 2 elements that this happens: 1*1 . Try a different initial array.

start quote.

``````for (int n = 0; n < adj2.length; n++) {
for (int m = 0; m < adj2.length; m++) {
for (int i = 0; i < adj2.length; i++) {
for (int j = 0; j < adj2.length; j++) {
}
if (path > 0) {
}
}
}
}
``````

end quote.

Just a suggestion: Don't you think this loop is a bit too nested? you could make your code much readable if you simplified these nested loops.

Edited by mike_2000_17: Fixed formatting

It is not clear what you are trying to do!

I can see how the first array adj[][] represents a directed graph but no lengths are given unless the lengths are the values in the array (ie. 1) Hence, you have no lengths to assess when the length is 2. It would seem you are actually looking for occasions when the paths can go both ways and extract a directional graph. This would occur when both adj[j] and adj[j] are none zero and could indeed be tested by the multiplication!
Where this is the case you then wish to insert 2 to mark a bidirectional connection at both adj2[j] and adj2[j]! As it stands you set the value in the adj2 array for independent indices of n and m, so it will set all values 2 once there is a birectional connection!

So, Agni is correct, you have too many nested loops, drop the outer loops for n and m and use

``````for (int i = 0; i < adj2.length; i++) {
for (int j = 0; j < adj2.length; j++) {
}
if (path > 0) {