#Mapping vertices to an index

9 messages · Page 1 of 1 (latest)

coarse cape
#

I am trying to implement dijkstras algorithm, to find the shortest path in a graph of vertices. I have looked at this C-implementation from rosetttacode: https://rosettacode.org/wiki/Dijkstra's_algorithm#C

In this implementation, the vertices are added to the graph array through this function

void add_vertex (graph_t *g, int i) {
    if (g->vertices_size < i + 1) {
        int size = g->vertices_size * 2 > i ? g->vertices_size * 2 : i + 4;
        g->vertices = realloc(g->vertices, size * sizeof (vertex_t *));
        for (int j = g->vertices_size; j < size; j++)
            g->vertices[j] = NULL;
        g->vertices_size = size;
    }
    if (!g->vertices[i]) {
        g->vertices[i] = calloc(1, sizeof (vertex_t));
        g->vertices_len++;
    }
}

My question is in regards to the second if statement, where the function checks if a vertex is already in the array. In the implementation, vertices are named from a-z, making it easy to map a vertex to an index: int v = a - 'a'. In my case however, there is more vertices than 26 vertices, and they would have a name field in the vertex struct. How would I map a vertex to an index in this case? My only idea is to do it through a hashmap, but maybe there is a more elegant solution. Let me know if I need to clarify, thanks 🙂

Rosetta Code

Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algo...

terse shoreBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

coarse cape
#

Basically I need to map a string to a number such that: "supermarket" = 0, "busstop" = 1, "cinema" = 3 and so on

chilly bay
#

do you know all the names at compile time?

#

then you can use an enum

#

so each vertex would store an enum value instead of a name

coarse cape
#

no, I should have mentioned that the vertices are unknown at compile time

chilly bay
#

then a hashmap probably makes sense, yeah

#

or you could store the int in the node itself