Two simple questions and my brain's not working. I'm using Floyd's Algorithm and trying to reconstruct the path taken from vertex U to vertex V. Here's my code to reconstruct the path.
public List<Integer> findCheapestPath(int u, int v)
{
if (u >= adjMatrix.length || v >= adjMatrix.length || u < 0 || v < 0)
{
throw new IllegalArgumentException("Error--Illegal Arugment Exception: One of the verticies are not valid.");
}
int intermediate;
intermediate = path[u][v];
if (intermediate == -1)
{
pathList.add(u);
return pathList;
} else
{
findCheapestPath(u, intermediate);
findCheapestPath(intermediate, v);
}
return pathList;
}
For one example, let u = 0 and v = 3, and let the shortest path from 0 to 3 be 0,1,2,3. However I have two problems. My pathList is an instance variable of the class and:
- I want the list to return "0,1,2,3" but it only returns "0,1,2", or if i replace pathList.add(u) with pathList.add(v), then it returns only "1,2,3" I could not figure out how to make it return the entire path including both end vertices. trying to put pathList.add(other vertex) will cause it to duplicate every intermediate vertex.
- When I call the method again, letting u = 3 and v = 0, and let the shortest path from 3 to 0 be "3,0" (already the shortest path), it just adds onto my previous list making it with my error from above "0,1,2,3" or "1,2,3,0" when it's supposed to be just "3,0"
Any help?