Maybe I am missing something that is clearly obvious but I have fiddled with this printHelper and print function for a while and cant seem to figure it out. The rest of the program works and gets the correct code, but this does not. It should print out 1 -> 3 -> 5

The shortest path from 1 to 5 has length 27 and is
1 -> 3 -> 1 -> 1 -> 0 next value is 5
1 next value is 1
2 next value is 1
3 next value is 1
4 next value is 1
5 next value is 3

I have a graph g that has a vertex* including next which is the number that comes previous to it. I have it so it sets them right but it is not outputting them correctly. Here is the print functions I am using.

``````// printPathHelper(Graph g, int start, int end) prints out the
// length of the shortest path from start vertex to finish vertex
// in Graph g
void printPathHelper(Graph g,int start,int n)
{
while(n != start)
{
n = g.info[n].next;
cout << n << " -> ";
printPathHelper(g,start,n);
}
}

// printPath(Graph g) prints out the shortest path
// from start vertex to finish vertex in Graph g
void printPath(Graph g, int start, int end)
{
cout << "The shortest path from " << start << " to " << end;
cout << " has length " << g.info[end].distance << " and is\n";
cout << start << " -> ";
printPathHelper(g,start,end);
//	cout << end << "\n";
}``````

start is the start vertex and end is the end vertex. Also, this code gets stuck in an infinite loop when it only had two vertices (i.e. 3 -> 2). Any reason as to why?

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Lerner

when you call printPathHelper function the 'n' parameter is ever going to be = to 'start' parameter?

How do you call this function? Do you send different values every call?