IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C Discussion :

programme algo de + court chemin (dijkstra)


Sujet :

C

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    80
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 80
    Par défaut programme algo de + court chemin (dijkstra)
    Bonjour

    j'ai trouvé un programme en C sur l'algo du Dijkstra du plus court chemin
    Le programme marche mais que je ne comprend pas trop comment il se déroule.

    l'algorithme lui se trouve ici :
    http://fr.wikipedia.org/wiki/Algorit...ra#Pseudo-code

    Pourriez vous m'expliquer s'il vou plait comment fonctionne ce programme?
    je l'ai compilé en C sur devc++
    je n'ai pas compris le role de toutes les matrices, ainsi que du booléen et le "array_D"

    merci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
     
    #include <stdio.h>
    #include <limits.h>
    #include <assert.h>
     
    typedef enum {false, true} bool; /* The order is rather important to
                                        get the boolean values right. */
    typedef char *string;
     
    #define oo UINT_MAX /* infinity is represented as the maximum unsigned int. */
     
    typedef unsigned int value;
     
    /* Firstly, the type of vertices for our particular graph (which was
       given as an example in the lectures). The (non)vertex `nonexistent'
       is used in order to indicate that a vertex (un sommet) hasn't got a predecessor
       in the path under consideration. See below. */
     
    typedef enum { A, B, C, D, nonexistent} vertex;
     
    /* If you modify the above, in order to consider a different graph,
       then you also have to modify the following. */
     
    const vertex first_vertex = A;
    const vertex last_vertex = D;
     
    #define no_vertices 4 // nombre de sommets
     
    /* Now a dictionary for output purposes. The order has to match the
       above, so that, for example, name[SFO]="SFO". */
     
    string name[] = {"A","B","C","D"};
     
    value weight[no_vertices][no_vertices] =
      {
       /*  A    B    C    D */
        {    0,   1,  2,  oo},  /* A */
        {   oo,   0,  1,   4},  /* B */
        {   oo,  oo,  0,   3},  /* C */
        {   2,   oo, oo,   0}   /* D */
      };
     
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *     
     * The implementation of Dijkstra's algorithm starts here. *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
     
    /* We first declare the array (ordre) `array_D' of overestimates, the array `tight' (serré)
       which records which of those estimates are actually tight, and the
       array `predecessor'. The last has the property that predecessor[z]
       is the last vertex visited on the way from the start node to z. */
     
    value array_D[no_vertices];          // coûts ou valeurs
    bool tight[no_vertices];
    vertex predecessor[no_vertices];    // sommets
     
    /* 
      We begin with the following auxiliary function, which should be
      called only when we know for sure that there is at least one node u
      with tight[u] false. Otherwise, the program aborts; this happens
      when the assertion below fails.
     */
     
    vertex minimal_nontight() {
     
      vertex j, u;
     
      for (j = first_vertex; j <= last_vertex; j++) 
         if (!tight[j]) 
            break;
     
      assert(j <= last_vertex);  // vérification que j est bien inférieur à last_vertex
     
      u = j; 
     
     /* Now u is the first vertex with nontight estimate, but not
         necessarily the one with minimal estimate, so we aren't done
         yet. */
     
      for (j++; j <= last_vertex; j++)
         if (!tight[j]  &&  array_D[j] < array_D[u])
              u = j;
     
      /* Having checked all vertices, we now know that u has the required
         minimality property. */ 
     
      return u;
    }
     
    /* 
       The following definition assumes that the graph is directed in
       general, which means that it would be wrong to have weight[z][u]
       instead. The intended meaning is that the vertex u has the vertex z
       as one of its successors. Recall that such a vertex z was
       called a neighbour of the vertex u, but this latter terminology is
       best reserved for undirected graphs. Notice that the example given
       above happens to be undirected. But, as remarked above, this
       program is intended to work for directed graphs as well. 
     */
     
    bool successor(vertex u, vertex z) {
      return (weight[u][z] != oo  &&  u != z);
    }
     
     
    /* 
      We finally arrive at the main algorithm. This is the same as given
      above, now written in C, with the computation of the actual
      paths included. The computation of paths is achieved via the use of
      the array `predecessor' declared above. Strictly speaking,
      Dijkstra's algorithm only records what is needed in order to recover
      the path. The actual computation of the path is performed by the
      algorithm that follows it.
     */
     
    void dijkstra(vertex s) {
     
      vertex z, u;
      int i;
     
      array_D[s] = 0;
     
      for (z = first_vertex; z <= last_vertex; z++) {
     
        if (z != s)
          array_D[z] = oo;
     
        tight[z] = false;
        predecessor[z] = nonexistent;
      }
     
      for (i = 0; i < no_vertices; i++) {
     
        u = minimal_nontight();
        tight[u] = true;
     
        /* In a disconnected graph, array_D[u] can be oo. But then we just move
           on to the next iteration of the loop. (Can you see why?) */
     
        if (array_D[u] == oo)
          continue; /* to next iteration ofthe for loop */
     
        for (z = first_vertex; z <= last_vertex; z++)
          if (successor(u,z) && !tight[z] && array_D[u] + weight[u][z] < array_D[z]) {
            array_D[z] = array_D[u] + weight[u][z]; /* Shortcut found. */
            predecessor[z] = u;
          }
      }
    }
     
    /* The conditions (successor(u,z) && !tight[z]) can be omitted from
       the above algorithm without changing its correctness. But I think
       that the algorithm is clearer with the conditions included, because
       it makes sense to attempt to tighten the estimate for a vertex only
       if the vertex is not known to be tight and if the vertex is a
       successor of the vertex under consideration. Otherwise, the
       condition (array_D[u] + weight[u][z] < array_D[z]) will fail anyway. However,
       in practice, it may be more efficient to just remove the conditions
       and only perform the test (array_D[u] + weight[u][z] < array_D[z]). */
     
    /* We can now use Dijkstra's algorithm to compute the shortest path
       between two given vertices. It is easy to go from the end of the
       path to the beginning. 
     
       To reverse the situation, we use a stack. Therefore we digress
       slightly to implement stacks (of vertices). In practice, one is
       likely to use a standard library instead, but, for teaching
       purposes, I prefer this program to be selfcontained. */
     
     
    #define stack_limit 10000 /* Arbitrary choice. Has to be big enough to
                                 accomodate the largest path. */
     
    vertex stack[stack_limit];
    unsigned int sp = 0; /* Stack pointer. */
     
    void push(vertex u) {
      assert(sp < stack_limit); /* We abort if the limit is exceeded. This
                                   will happen if a path with more
                                   vertices than stack_limit is found. */
      stack[sp] = u;
      sp++;
    }
     
    bool stack_empty() {
      return (sp == 0);
    }
     
    vertex pop() {
      assert(!stack_empty()); /* We abort if the stack is empty. This will
                                 happen if this program has a bug. */
      sp--;
      return stack[sp];
    }
     
    /* End of stack digression and back to printing paths. */
     
     
    void print_shortest_path(vertex origin, vertex destination) {
     
      vertex v;
     
      assert(origin != nonexistent  &&  destination != nonexistent);
     
      dijkstra(origin);
     
      printf("The shortest path from %s to %s is:\n\n",
             name[origin], name[destination]);
     
      for (v = destination; v != origin; v = predecessor[v])
        if (v == nonexistent) {
          printf("nonexistent (because the graph is disconnected).\n");
          return;
        }
        else
          push(v);
     
      push(origin); 
     
      while (!stack_empty()) 
        printf(" %s",name[pop()]);
     
      printf(".\n\n");
    }
     
     
    /* We now run an example. */
     
    int main() {
     
      print_shortest_path(C,A);   // de C à A
      getch();
      return 0; /* Return gracefully to the caller of the program
                   (provided the assertions above haven't failed). */
    }
    merci

  2. #2
    Membre éprouvé
    Avatar de granquet
    Profil pro
    Étudiant
    Inscrit en
    Octobre 2005
    Messages
    1 201
    Détails du profil
    Informations personnelles :
    Localisation : France, Pyrénées Orientales (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2005
    Messages : 1 201
    Par défaut
    l'explication ... c'est l'algo !

    et :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    value weight[no_vertices][no_vertices] =
      {
       /*  A    B    C    D */
        {    0,   1,  2,  oo},  /* A */
        {   oo,   0,  1,   4},  /* B */
        {   oo,  oo,  0,   3},  /* C */
        {   2,   oo, oo,   0}   /* D */
      };
    est une representation de ton graphe:
    oo: infini => pas d'arc
    autre: cout de l'arc

    (exemples pris dans le desordre)
    pas d'ars de A vers B,
    arc de B vers A avec un cout de 1
    arc de D vers B avec un cout de 4 ...

    etc ...

    j'ai pas trop le temps d'en dire plus (mon reveil sonne dans 6h ... pour 4h de cours d'algo !), lis bien les commentaires, relis bien l'algo ... ça devrais te paraitre evident.

  3. #3
    Expert confirmé
    Avatar de Thierry Chappuis
    Homme Profil pro
    Enseignant Chercheur
    Inscrit en
    Mai 2005
    Messages
    3 499
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Mai 2005
    Messages : 3 499
    Par défaut
    La démarche est de comprendre l'algo de recherche du plus court chemin de Dijkstra de manière indépendante du langage. Voir un ouvrage de référence sur l'algorithmique, ou sur le web (je trouve ça étrange que sur Wikipedia, on trouve des exemples en C. Du pseudo code serait mieux venu). Si tu as des questions ensuite, l'excellent forum d'algorithmique de developpez.com est là pour t'aider dans ta compréhension.

    Une fois l'algo compris, l'interprétation de son implémentation C ne devrait plus poser beaucoup de problème et le forum C est là pour répondre aux question de détails qui concerne le C.

    Bonne chance

    Thierry
    "The most important thing in the kitchen is the waste paper basket and it needs to be centrally located.", Donald Knuth
    "If the only tool you have is a hammer, every problem looks like a nail.", probably Abraham Maslow

    FAQ-Python FAQ-C FAQ-C++

    +

  4. #4
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    80
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2003
    Messages : 80
    Par défaut
    merci pour vos réponses mais ça je sais

    moi c plus comparaison programme avec l'algorithme
    par exemple pourquoi il y a "typedef enum {false, true} bool; ", ça va servir à quoi comparé à l'algo ?

    c quoi les trucs tight et le nontight? (tableaux pour quoi faire?)
    et les vertex u et z ?
    enfin le nonexistant y a pas ça dans l'algo.


    voilà ce que je n'ai pas compris, c le déroulement par rapport à l'algo.

    merci d'avance pour votre aide

  5. #5
    Membre éclairé
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    67
    Détails du profil
    Informations personnelles :
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Juin 2006
    Messages : 67
    Par défaut Dijkstra
    Salut !
    bon apparemment tu mas l'air un peu perdu !!
    je lai implémenter ya un moment cet algo !!
    t'occupe pas de l'implémentation , en plus c en anglais les vertex , et les enum c une manière d'écrire son code en c , y a mille manière de le faire !!
    l'essentiel c ton algo faudra qu'il soi bon !
    donc si on a bien compris a quoi ça sert c d'afficher le plus court chemin d'un sommet donné vers les autres sommet d'un graphe !
    donc un tableau ou tu mettra la distance qui te servira de poids pour les arêtes de ton graphe ( poids >=0) pour que tu puisse afficher a la fin ton plus court chemin ... bref je pense que je ne suis pas très clair !
    mais un algo c une chose et l'implementation ça reste perso !
    chacun sa façon de programmer

  6. #6
    Membre éprouvé
    Homme Profil pro
    Inscrit en
    Octobre 2006
    Messages
    132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations forums :
    Inscription : Octobre 2006
    Messages : 132
    Par défaut
    Cours et tutoriels C : http://c.developpez.com/cours/

Discussions similaires

  1. Algoritme Dijkstra pour le calcul du plus court chemin
    Par choko83 dans le forum Langage
    Réponses: 2
    Dernier message: 10/06/2010, 14h10
  2. Plus court chemin Dijkstra STL
    Par CedricMocquillon dans le forum C++
    Réponses: 6
    Dernier message: 05/10/2007, 16h44
  3. [algo] plus courts chemins (au pluriel !!)
    Par ADSL[fx] dans le forum Algorithmes et structures de données
    Réponses: 9
    Dernier message: 18/01/2006, 14h40
  4. algo de Dijkstra (+ court chemin d'un labyrinthe)
    Par gg14bis dans le forum Algorithmes et structures de données
    Réponses: 5
    Dernier message: 25/03/2005, 08h57

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo