This guide explains Bellman-Ford from first principles. The goal is to understand the problem it solves, why the algorithm works, how to implement it, and where it appears in real software systems.
What problem does it solve?
Bellman-Ford belongs to the graph-algorithm toolbox. Before coding, define what the vertices represent, what an edge means, and what result the system actually needs.
The core idea in simple terms
تمام یالها را بارها Relax میکنیم تا فاصلهها دیگر بهتر نشوند.
Step-by-step process
- فاصله مبدأ صفر و بقیه Infinity.
- تمام یالها را V-1 بار Relax میکنیم.
- اگر مسیر جدید کوتاهتر بود dist را آپدیت میکنیم.
- یک دور اضافه برای تشخیص negative cycle اجرا میکنیم.
JavaScript example
function bellmanFord(vertices, edges, source) {
const dist = Object.fromEntries(vertices.map(v => [v, Infinity]));
dist[source] = 0;
for (let i = 0; i < vertices.length - 1; i++)
for (const [u,v,w] of edges)
if (dist[u] !== Infinity && dist[u] + w < dist[v]) dist[v] = dist[u] + w;
for (const [u,v,w] of edges)
if (dist[u] !== Infinity && dist[u] + w < dist[v])
throw new Error("Negative cycle");
return dist;
}Real-world and workplace examples
- مدلهای سود/زیان
- Distance Vector Routing
- Credit/Penalty Graph
- تشخیص Negative Cycle
Time and space complexity
O(VE) time و O(V) space
When should you use it?
Use it when the problem matches this condition: وجود وزن منفی یا نیاز به تشخیص چرخه منفی.
When is it not a good fit?
It is usually not the best choice when: با وزنهای غیرمنفی Dijkstra معمولاً سریعتر است..
Summary
Do not choose an algorithm by name alone. First identify whether the graph is directed or undirected, weighted or unweighted, and whether the goal is traversal, reachability, shortest path, connectivity, spanning structure, or combinatorial optimization.