_bellman_ford.c
Upload User: gzelex
Upload Date: 2007-01-07
Package Size: 707k
Code Size: 2k
Development Platform:

MultiPlatform

  1. /*******************************************************************************
  2. +
  3. +  LEDA-R  3.2.3
  4. +
  5. +  _bellman_ford.c
  6. +
  7. +  Copyright (c) 1995  by  Max-Planck-Institut fuer Informatik
  8. +  Im Stadtwald, 66123 Saarbruecken, Germany     
  9. +  All rights reserved.
  10. *******************************************************************************/
  11. /*******************************************************************************
  12. *                                                                              *
  13. *  BELLMAN FORD                                                                *
  14. *                                                                              *
  15. *******************************************************************************/
  16. #include <LEDA/graph_alg.h>
  17. #include <LEDA/b_queue.h>
  18. bool BELLMAN_FORD(const graph& G, node s, const edge_array<num_type>& cost, 
  19.                                                 node_array<num_type>& dist, 
  20.                                                 node_array<edge>& pred ) 
  21. /* single source shortest paths from s using a queue (breadth first search)
  22.    computes for all nodes v:
  23.    a) dist[v] = cost of shortest path from s to v
  24.    b) pred[v] = predecessor edge of v in shortest paths tree
  25. */
  26.   node_array<int> count(G,0);
  27.   int n = G.number_of_nodes();
  28.   node_list Q;
  29.   node u,v;
  30.   edge e;
  31.   forall_nodes(v,G) 
  32.   { pred[v] = 0;
  33.     dist[v] = max_num; 
  34.    }
  35.   dist[s] = 0;
  36.   Q.append(s);
  37.   while(! Q.empty() )
  38.   { u = Q.pop();
  39.     if (++count[u] > n) return false;   // negative cycle
  40.     num_type du = dist[u];
  41.     forall_adj_edges(e,u) 
  42.     { v = target(e);
  43.       num_type c = du + cost[e];
  44.       if (c < dist[v]) 
  45.       { dist[v] = c; 
  46.         pred[v] = e;
  47.         if (!Q.member(v)) Q.append(v);
  48.        }
  49.      } 
  50.    }
  51.   return true;
  52. }