home *** CD-ROM | disk | FTP | other *** search
- /*******************************************************************************
- +
- + LEDA 2.1.1 11-15-1991
- +
- +
- + _bellman_ford.c
- +
- +
- + Copyright (c) 1991 by Max-Planck-Institut fuer Informatik
- + Im Stadtwald, 6600 Saarbruecken, FRG
- + All rights reserved.
- +
- *******************************************************************************/
-
-
-
- /*******************************************************************************
- * *
- * BELLMAN FORD *
- * *
- *******************************************************************************/
-
-
-
-
- #include <LEDA/graph_alg.h>
- #include <LEDA/b_queue.h>
-
- declare(b_queue,node)
-
- bool BELLMAN_FORD(const graph& G, node s, const edge_array(int)& cost,
- node_array(int)& dist,
- node_array(edge)& pred )
-
- /* single source shortest paths from s using a queue (breadth first search)
- computes for all nodes v:
- a) dist[v] = cost of shortest path from s to v
- b) pred[v] = predecessor edge of v in shortest paths tree
- */
-
- {
- node_array(bool) in_Q(G,false);
- node_array(int) count(G,0);
-
- int n = G.number_of_nodes();
- b_queue(node) Q(n);
-
- node u,v;
- edge e;
- int c;
-
- forall_nodes(v,G)
- { pred[v] = 0;
- dist[v] = Infinity;
- }
-
- dist[s] = 0;
- Q.append(s);
- in_Q[s] = true;
-
- while (!Q.empty())
- { u = Q.pop();
- in_Q[u] = false;
-
- if (++count[u] > n) return false;
-
- forall_adj_edges(e,u)
- { v = target(e);
- c = dist[u] + cost[e];
-
- if (c < dist[v])
- { dist[v] = c;
- pred[v] = e;
- if (!in_Q[v])
- { Q.append(v);
- in_Q[v]=true;
- }
-
- }
-
- } /* forall */
-
- } // while
-
- return true;
-
- }
-
-
-
- #ifndef NO_REAL_GRAPH_ALG
-
-
- // BELLMAN_FORD for real valued edge costs:
-
- bool BELLMAN_FORD(const graph& G, node s, const edge_array(real)& cost,
- node_array(real)& dist,
- node_array(edge)& pred )
-
- { int n = G.number_of_nodes();
- b_queue(node) Q(n);
- node_array(bool) in_Q(G,false);
- node_array(int) count(G,0);
-
- node u,v;
- edge e;
- real c;
-
- forall_nodes(v,G)
- { pred[v] = 0;
- dist[v] = Infinity;
- }
-
- dist[s] = 0;
- Q.append(s);
- in_Q[s] = true;
-
- while (!Q.empty())
- { u = Q.pop();
- in_Q[u] = false;
-
- if (++count[u] > n) return false;
-
- forall_adj_edges(e,u)
- { v = target(e);
- c = dist[u] + cost[e];
-
- if (c < dist[v])
- { dist[v] = c;
- pred[v] = e;
- if (!in_Q[v])
- { Q.append(v);
- in_Q[v] = true;
- }
-
- }
-
- } /* forall */
-
- } // while
-
- return true;
-
- }
-
- #endif
-