According to your question, I get the parent array as:
int parent[] = {-1,0,1,2,5,6,7,0,2};
I also run your code :
void printPath(int parent[], int j)
{
int temp = parent[j];
while (temp != - 1)
{
temp = parent[temp];
printf("%d ", temp);
}
}
Now three things to note:
1) Initialize int temp = j and not with parent[j]. This makes sure that you start with your path from j and not from parent[j].
2) Instead of doing this:
temp = parent[temp];
printf("%d ", temp);
do this:
printf("%d ", temp);
temp = parent[temp];
This makes sure that you first print j and then parent[j].
After making the above changes your output will look like this:
1 0
2 1 0
3 2 1 0
4 5 6 7 0
5 6 7 0
6 7 0
7 0
8 2 1 0
Now the last note.
3) To get the desired output you need to print in reverse order. One way is to first count the elements in the path. Then create an array of that size. Traverse again starting from j and store the elements in the array. After that you can print the array in reverse order.
After making these changes we get the following code:
void printPath(int parent[], int j)
{
// Initialized temp from j
int temp = j;
// int variable that will store the number of elements in path
int cnt=0;
// traversing the path for first time to get count of elements in path
while (temp != - 1)
{
cnt++;
temp = parent[temp];
}
// creating array of cnt size
int arr[cnt];
// traversing the path for second time.
// this time we will store elements in the array
temp = j;
int i=0;
while(temp!=-1){
arr[i++]=temp;
temp = parent[temp];
}
// printing the elements in reverse order
for(int i=cnt-1;i>=0;i--)
printf("%d ",arr[i]);
}
The above code will give you the correct output (as you mentioned):
0 1
0 1 2
0 1 2 3
0 7 6 5 4
0 7 6 5
0 7 6
0 7
0 1 2 8