// apply Bellman-Ford's algorithm from source // // source = the source for the computing distances // nodes = list of all nodes from G // edges = list of all edges from G // // returns: has_cycle, d, p // has_cycle = negative cycle detection flag (true if found) // d = distance vector (defined only if has_cycle == false) // p = parent vector (defined only if has_cycle == false) // Bellman-Ford(source, G=(nodes, edges)) { // STEP 0: initialize results // d[node] = distance from source to node // p[node] = parent of node on the shortest path from source to node foreach (node in nodes) { d[node] = +oo; // distance not yet computed p(node) = null; // parent not yet found } // STEP 1: set distance and parent for source node d[source] = 0; // distance from source to source p[source] = null; // source never has parent // STEP 2: do |nodes| - 1 relaxations for all edges in G for (i = 1 : |nodes| - 1) { foreach ((node, neigh) in edges) { if (d[node] + w[node][neigh] < d[neigh]) { // try to relax edge (node, neigh) d[neigh] = d[node] + w[node][neigh]; // update the new distance from source to neigh p[neigh] = node; // save parent } } } // STEP 3: check if edge relaxations can still be made foreach ((node, neigh) in edges) { if (d[node] + w[node][neigh] < d[neigh]) { // try to relax edge (node, neigh) // negative cycle detected! return true, null, null; } } // STEP 4: no cycle detected return false, d, p; } // Usage example: has_cycle, d, p = Bellman-Ford(source, G=(nodes, edges)); if (has_cycle) { print "Has Cycle!" STOP. } else { // 1. Use distances from d // (e.g. d[node] = distance from source to node) // // 2. Rebuild path from node to source using parents (p) RebuildPath(source, destination, p); }