Home > Enterprise >  How to print SSSP in order in C?
How to print SSSP in order in C?

Time:01-19

I have a working code that prints the SSSP from destination to source, but I want it to be in reverse i.e. source to destination.

Let's say that this generates a path of 10 9 0 and another that is 5 7 0, where 3 is the destination and 1 is the source/starting node.

I want it to print 0 9 10 and 0 5 7 instead.

CodePudding user response:

You can consider using the stack to store the traversal results first, and then outputting the contents of the stack should give you the result you want.

CodePudding user response:

Use a recursive path printer. You have:

for (i = 1; i <= T->vertices; i  )
{
    if (T->parent[i] != -1)
    {
        printf("SSSP Distance from %d->%d is %d: {%d",
               T->visited[i], i, T->distance[i], i);

        j = i;
        while(T->parent[j] != -1)
        {   //the path is printed backwards, but still in order.
            j = T->parent[j];
            printf("<-%d", j);
        }
        printf("}\n");
    }   
}

Consider adding a function:

static void path_printer(SomeType *T, size_t i)
{
    size_t j = T->parent[i];
    if (j != -1)
    {
        path_printer(T, j);
        if (T->parent[j] != -1)
            printf("->");
        printf("%d", i);
     }
}

and revise your loop to:

for (i = 1; i <= T->vertices; i  )
{
    if (T->parent[i] != -1)
    {
        printf("SSSP Distance from %d->%d is %d: {",
               T->visited[i], i, T->distance[i]);
        path_printer(T, i);
        printf("}\n");
    }   
}

The recursive function prints the list items in reverse order; the rest is cosmetic.

Caution: untested code!

Since the question does not provide an MCVE (Minimal, Complete, Verifiable Example — or MRE or whatever name SO now uses) or an SSCCE (Short, Self-Contained, Correct Example — the same idea by a different name), it is not possible to test this proposed solution. I had to guess the name of the type of the variable T — I think it is a SomeType *.

  •  Tags:  
  • c
  • Related