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

instead i get this
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?

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?

Those questions might give you an answer to your problem.

You want to stop when n == end, not when n == start. The first value of n is start and you should never get back there again, if you aren't going to visit any vertex more than once.

Try changing line 21 to printPathHelper(g, end, start);
Change parameters in line 4 to: Graph g, int end, int n
Change start in line 6 and 10 to end.

Drop this:
" -> "
from line 20, output it between lines 7 and 8 and remove the display of the arrow on line 9. Otherwise you will have an arrow at the end of the display that points to nowhere.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.