ā¹ļø Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python |
| Last Crawled | 2026-03-13 15:16:40 (29 days ago) |
| First Indexed | not set |
| HTTP Status Code | 200 |
| Meta Title | Implementation of Bellman-Ford algorithm in python - Stack Overflow |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | This code does not work for graphs that are not connected
eg it gives 1 for the following case which is correct:
edges = []
edges.append([0, 1, 5])
edges.append([2, 3, -5])
edges.append([3, 4, -6])
edges.append([4, 2, -5])
edges.append([1, 2, 5])
print(bellmanFord(5, edges))
Link to demo :
http://ideone.com/j8XAs3
and when we remove the edge 1 -> 2 it gives it gives 0, even though the graph has a negative cycle (2 -> 3 -> 4 -> 2) :
edges = []
edges.append([0, 1, 5])
edges.append([2, 3, -5])
edges.append([3, 4, -6])
edges.append([4, 2, -5])
print(bellmanFord(5, edges))
Link to demo :
http://ideone.com/N4Bljk
EDIT:
As you said that the test case #12 passed after you used every vertex as source, I do believe that the graph is not connected, the problem is that the time complexity of the solution has increased it is now
O(n*n*m)
i.e about 10^11 operations that is certain to time out.
So you can modify the algorithm in the following way :
1) Find all the connected components and separate out the vertices and edges for that component and create a new graphs with those vertices and edges
2) Suppose you have k new graphs now, run Bellman Ford on each of them.
Also you are using the word "strongly connected" in the wrong way, a directed graph is strongly connected if there is a path from every vertex to every other possible vertex.
I saw the question that you are referring to, I assume it is "Problem: Detecting Anomalies in Currency Exchange Rates" if I am right regarding the question then the example given in the question contradicts the fact that it is strongly connected as there is no way to reach the vertex 4, the graph however is connected.
Example in the question :
4 4
1 2 -5
4 1 2
2 3 2
3 1 1
Do let me know if it is not the question you are referring to, or if you have some other doubts. |
| Markdown | [Skip to main content](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python#content)
1. [About](https://stackoverflow.co/)
2. Products
3. [For Teams](https://stackoverflow.co/internal/)
4. Try new site Try BETA
1. [Stack Internal Implement a knowledge platform layer to power your enterprise and AI tools.](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams)
2. [Stack Data Licensing Get access to top-class technical expertise with trusted & attributed content.](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api)
3. [Stack Ads Connect your brand to the worldās most trusted technologist communities.](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising)
4. [Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal.](https://stackoverflow.blog/releases/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=releases)
5. [About the company](https://stackoverflow.co/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=about-the-company) [Visit the blog](https://stackoverflow.blog/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=blog)
1. ### [current community](https://stackoverflow.com/)
- [Stack Overflow](https://stackoverflow.com/)
[help](https://stackoverflow.com/help) [chat](https://chat.stackoverflow.com/?tab=explore)
- [Meta Stack Overflow](https://meta.stackoverflow.com/)
### your communities
[Sign up](https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F41517416%2Fimplementation-of-bellman-ford-algorithm-in-python) or [log in](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F41517416%2Fimplementation-of-bellman-ford-algorithm-in-python) to customize your list.
### [more stack exchange communities](https://stackexchange.com/sites)
[company blog](https://stackoverflow.blog/)
2. [Log in](https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F41517416%2Fimplementation-of-bellman-ford-algorithm-in-python)
3. [Sign up](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F41517416%2Fimplementation-of-bellman-ford-algorithm-in-python)
1. 1. [Home](https://stackoverflow.com/)
2. [Questions](https://stackoverflow.com/questions)
3. [AI Assist](https://stackoverflow.com/ai-assist)
4. [Tags](https://stackoverflow.com/tags)
5. [Challenges](https://stackoverflow.com/beta/challenges)
6. [Chat](https://chat.stackoverflow.com/?tab=explore)
7. [Articles](https://stackoverflow.blog/contributed?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=so-blog&utm_content=experiment-articles)
8. [Users](https://stackoverflow.com/users)
9. [Companies](https://stackoverflow.com/jobs/companies?so_medium=stackoverflow&so_source=SiteNav)
10. [Collectives]()
11. Communities for your favorite technologies. [Explore all Collectives](https://stackoverflow.com/collectives-all)
2. Stack Internal
Stack Overflow for Teams is now called **Stack Internal**. Bring the best of human thought and AI automation together at your work.
[Try for free](https://stackoverflowteams.com/teams/create/free/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams) [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams)
3. [Stack Internal]()
4. Bring the best of human thought and AI automation together at your work. [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact)
##### Collectives⢠on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
[Learn more about Collectives](https://stackoverflow.com/collectives)
**Stack Internal**
Knowledge at work
Bring the best of human thought and AI automation together at your work.
[Explore Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact-popover)
# [Implementation of Bellman-Ford algorithm in python](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python)
[Ask Question](https://stackoverflow.com/questions/ask)
Asked
9 years, 2 months ago
Modified [7 years, 8 months ago](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python?lastactivity "2018-06-30 17:26:26Z")
Viewed 6k times
2
I am doing an exercise for the course "Algorithms on Graphs" on Coursera and I have to implement the Bellman-Ford algorithm to detect if a graph has a negative cycle or not, outputting 1 and 0 respectively. I did a lot of stress testing and my implementation works fine, but it fails on one of the test cases on the course (but they don't give any information about it, other than "wrong answer"). My implementation is just the same one you find all over the web, and because of that I can't see what is wrong with my code. Any ideas?
```
def relax(u,v,w,dist,prev):
if dist[u]+w < dist[v]:
dist[v] = dist[u]+w
prev[v] = u
def bellmanFord(V,E):
dist = [float('inf')] * V
prev = [None] * V
dist[0] = 0
for i in range(V-1):
for edge in E:
relax(edge[0],edge[1],edge[2],dist,prev)
#checks for negative cycles
for e in E:
u = e[0]
v = e[1]
w = e[2]
if dist[u]+w < dist[v]:
return 1
return 0
```
- [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'")
- [algorithm](https://stackoverflow.com/questions/tagged/algorithm "show questions tagged 'algorithm'")
- [graph](https://stackoverflow.com/questions/tagged/graph "show questions tagged 'graph'")
- [shortest-path](https://stackoverflow.com/questions/tagged/shortest-path "show questions tagged 'shortest-path'")
[Share](https://stackoverflow.com/q/41517416 "Short permalink to this question")
[Improve this question](https://stackoverflow.com/posts/41517416/edit)
Follow
[edited Jun 30, 2018 at 17:26](https://stackoverflow.com/posts/41517416/revisions "show all edits to this post")
[](https://stackoverflow.com/users/1193874/paul)
[Paul](https://stackoverflow.com/users/1193874/paul)
5,97511 gold badge3434 silver badges3737 bronze badges
asked Jan 7, 2017 at 3:12
[](https://stackoverflow.com/users/3182733/tortov)
[tortov](https://stackoverflow.com/users/3182733/tortov)
9122 silver badges77 bronze badges
5
- They don't test the empty graph, do they?
David Eisenstat
ā [David Eisenstat](https://stackoverflow.com/users/2144669/david-eisenstat "65,748 reputation")
2017-01-07 04:19:29 +00:00
Commented Jan 7, 2017 at 4:19
- Or a graph that's not strongly connected?
David Eisenstat
ā [David Eisenstat](https://stackoverflow.com/users/2144669/david-eisenstat "65,748 reputation")
2017-01-07 04:20:09 +00:00
Commented Jan 7, 2017 at 4:20
- Are weights in the input floating point or integer? Is it guaranteed the graph is connected?
kraskevich
ā [kraskevich](https://stackoverflow.com/users/2040251/kraskevich "18,596 reputation")
2017-01-07 08:05:28 +00:00
Commented Jan 7, 2017 at 8:05
- All graphs are directed, have weights as integers at most 10³, N edges between 1 and 10³, M edges between 0 and 10ā“. The graphs are not strongly connected. This code works when there is 1 or more vertices and no edges, or when there is a loop (if a vertex connects with itself and has a negative weight the program detects a negative cycle). Any kind of graph with positive weights is detected as not having negative cycles. What is happening is that some graph with negative weights is being considered as a negative cycle, or not when it should be, but I can't find a wrong test case.
tortov
ā [tortov](https://stackoverflow.com/users/3182733/tortov "91 reputation")
2017-01-07 11:56:32 +00:00
Commented Jan 7, 2017 at 11:56
- Cross-posted: [stackoverflow.com/q/41517416/781723](http://stackoverflow.com/q/41517416/781723), [cs.stackexchange.com/q/68357/755](http://cs.stackexchange.com/q/68357/755). Please [do not post the same question on multiple sites](http://meta.stackexchange.com/q/64068). Each community should have an honest shot at answering without anybody's time being wasted.
D.W.
ā [D.W.](https://stackoverflow.com/users/781723/d-w "3,745 reputation")
2017-01-07 17:52:47 +00:00
Commented Jan 7, 2017 at 17:52
[Add a comment](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.") \|
## 2 Answers 2
Sorted by:
[Reset to default](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python?answertab=scoredesc#tab-top)
1
This code does not work for graphs that are not connected eg it gives 1 for the following case which is correct:
```
edges = []
edges.append([0, 1, 5])
edges.append([2, 3, -5])
edges.append([3, 4, -6])
edges.append([4, 2, -5])
edges.append([1, 2, 5])
print(bellmanFord(5, edges))
```
Link to demo : <http://ideone.com/j8XAs3>
and when we remove the edge 1 -\> 2 it gives it gives 0, even though the graph has a negative cycle (2 -\> 3 -\> 4 -\> 2) :
```
edges = []
edges.append([0, 1, 5])
edges.append([2, 3, -5])
edges.append([3, 4, -6])
edges.append([4, 2, -5])
print(bellmanFord(5, edges))
```
Link to demo : <http://ideone.com/N4Bljk>
***
EDIT:
As you said that the test case \#12 passed after you used every vertex as source, I do believe that the graph is not connected, the problem is that the time complexity of the solution has increased it is now `O(n*n*m)` i.e about 10^11 operations that is certain to time out.
So you can modify the algorithm in the following way :
1\) Find all the connected components and separate out the vertices and edges for that component and create a new graphs with those vertices and edges
2\) Suppose you have k new graphs now, run Bellman Ford on each of them.
Also you are using the word "strongly connected" in the wrong way, a directed graph is strongly connected if there is a path from every vertex to every other possible vertex.
I saw the question that you are referring to, I assume it is "Problem: Detecting Anomalies in Currency Exchange Rates" if I am right regarding the question then the example given in the question contradicts the fact that it is strongly connected as there is no way to reach the vertex 4, the graph however is connected.
Example in the question :
```
4 4
1 2 -5
4 1 2
2 3 2
3 1 1
```
Do let me know if it is not the question you are referring to, or if you have some other doubts.
[Share](https://stackoverflow.com/a/41523104 "Short permalink to this answer")
[Improve this answer](https://stackoverflow.com/posts/41523104/edit)
Follow
[edited Jan 7, 2017 at 20:52](https://stackoverflow.com/posts/41523104/revisions "show all edits to this post")
answered Jan 7, 2017 at 15:35
[](https://stackoverflow.com/users/2955869/useemsurprised)
[uSeemSurprised](https://stackoverflow.com/users/2955869/useemsurprised)
1,83422 gold badges1515 silver badges1818 bronze badges
Sign up to request clarification or add additional context in comments.
## 3 Comments
Add a comment
[](https://stackoverflow.com/users/3182733/tortov)
tortov
[tortov](https://stackoverflow.com/users/3182733/tortov)
[Over a year ago](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python#comment70257374_41523104)
Thanks for the answer uSeemSurprised. Actually I was wrong, all the graphs must be strongly connected. If I understood well, the Bellman-Ford algorithm is a single source shortest path algorithm, so this means that it can only find negative cycles connected to the source. But your post helped me get a hint about the problem. Applying the BellmanFord function with each vertex as source, I was able to pass the exercise (\#12), going up to \#18, but failed because it took too much time. Probably my code isn't detecting the correct distances and left some vertex out in a strongly connected graph.
2017-01-07T19:45:40Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/3182733/tortov)
tortov
[tortov](https://stackoverflow.com/users/3182733/tortov)
[Over a year ago](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python#comment70269888_41523104)
Thanks again for the answer. That is the problem in question. I made a reachability function that marks each node wih a group number. So in the example if I start at 1, the vertices 1, 2, 3 would be marked as "0" and 4 would be marked as "1". If the start was 4, everyone would be on group "0". In both cases it works. I run the bellmanFord in the first member of ech group then. With this I was able to pass case \#12, but got stuck on case \#18 again. This time it took only 0.13 seconds and got a "Wrong answer". Because of the time it took I think that it is detecting a false negative cycle.
2017-01-08T11:58:32.673Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/3182733/tortov)
tortov
[tortov](https://stackoverflow.com/users/3182733/tortov)
[Over a year ago](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python#comment70270057_41523104)
If I run the bellmanFord in the inverse order, starting from the last group, the program fails at code \#12 again, but now because of a timeout. If it finds a negative cycle it return immediately, and that's what must be happening in case \#18. Both \#12 and \#18 must have a huge number of vertices and edges. Anyway, now I must find a test case that makes it fail. Here is the updated code:<http://ideone.com/cczJjq>
2017-01-08T12:08:37.013Z+00:00
0
Reply
- Copy link
Add a comment
1
So, I found the solution for the exercise and it was pretty simple. The problem was using float('inf') to initialize the dist list. If instead I use a huge number, like 10000000 it works fine on my initial code, without the need to scan all the vertices. It works algo in the example of a not connected graph. Thanks forr the help, I learned a lot\!
[Share](https://stackoverflow.com/a/41534958 "Short permalink to this answer")
[Improve this answer](https://stackoverflow.com/posts/41534958/edit)
Follow
answered Jan 8, 2017 at 16:32
[](https://stackoverflow.com/users/3182733/tortov)
[tortov](https://stackoverflow.com/users/3182733/tortov)
9122 silver badges77 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/2955869/useemsurprised)
uSeemSurprised
[uSeemSurprised](https://stackoverflow.com/users/2955869/useemsurprised)
[Over a year ago](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python#comment70288402_41534958)
Using infinity is always a good idea as you may not know how large the values are, try out the python code that is given in the link that I have provided, it is a much cleaner way, link : [geeksforgeeks.org/ā¦](http://www.geeksforgeeks.org/dynamic-programming-set-23-bellman-ford-algorithm/)
2017-01-09T05:51:52.37Z+00:00
0
Reply
- Copy link
Start asking to get answers
Find the answer to your question by asking.
[Ask question](https://stackoverflow.com/questions/ask)
Explore related questions
- [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'")
- [algorithm](https://stackoverflow.com/questions/tagged/algorithm "show questions tagged 'algorithm'")
- [graph](https://stackoverflow.com/questions/tagged/graph "show questions tagged 'graph'")
- [shortest-path](https://stackoverflow.com/questions/tagged/shortest-path "show questions tagged 'shortest-path'")
See similar questions with these tags.
- The Overflow Blog
- [Even the chip makers are making LLMs](https://stackoverflow.blog/2026/03/10/even-the-chip-makers-are-making-llms/)
- [Open source for awkward robots](https://stackoverflow.blog/2026/03/13/open-source-for-awkward-robots/)
- Featured on Meta
- [Logo updates to Stack Overflow's visual identity](https://meta.stackexchange.com/questions/417394/logo-updates-to-stack-overflows-visual-identity)
- [Policy: Generative AI (e.g., ChatGPT) is banned](https://meta.stackoverflow.com/questions/421831/policy-generative-ai-e-g-chatgpt-is-banned)
- [Release notes and bug fixes for beta.stackoverflow.com](https://meta.stackoverflow.com/questions/438499/release-notes-and-bug-fixes-for-beta-stackoverflow-com)
- [Iām Jody, the Chief Product and Technology Officer at Stack Overflow. Letās...](https://meta.stackoverflow.com/questions/438369/i-m-jody-the-chief-product-and-technology-officer-at-stack-overflow-let-s-talk "Iām Jody, the Chief Product and Technology Officer at Stack Overflow. Letās talk about the site redesign")
#### Related
[4](https://stackoverflow.com/questions/997104/performance-of-bellman-ford-shortest-path-algorithm "Question score (upvotes - downvotes)")
[Performance of BellmanāFord shortest path algorithm](https://stackoverflow.com/questions/997104/performance-of-bellman-ford-shortest-path-algorithm)
[6](https://stackoverflow.com/questions/11369829/bellman-ford-all-shortest-paths "Question score (upvotes - downvotes)")
[Bellman-Ford: all shortest paths](https://stackoverflow.com/questions/11369829/bellman-ford-all-shortest-paths)
[1](https://stackoverflow.com/questions/15983747/why-this-implementation-of-bellman-ford-doesnt-work "Question score (upvotes - downvotes)")
[Why this implementation of Bellman-Ford doesn't work?](https://stackoverflow.com/questions/15983747/why-this-implementation-of-bellman-ford-doesnt-work)
[1](https://stackoverflow.com/questions/20349609/shortest-path-with-bfs-output-graph "Question score (upvotes - downvotes)")
[Shortest path with BFS output graph](https://stackoverflow.com/questions/20349609/shortest-path-with-bfs-output-graph)
[1](https://stackoverflow.com/questions/26957510/queue-based-bellman-ford-algorithm "Question score (upvotes - downvotes)")
[Queue-based Bellman-Ford algorithm](https://stackoverflow.com/questions/26957510/queue-based-bellman-ford-algorithm)
[5](https://stackoverflow.com/questions/29817131/bellman-ford-queue-based-approach-from-sedgewick-and-wayne-algorithms-4th-edi "Question score (upvotes - downvotes)")
[Bellman ford queue based approach from Sedgewick and Wayne - Algorithms, 4th edition](https://stackoverflow.com/questions/29817131/bellman-ford-queue-based-approach-from-sedgewick-and-wayne-algorithms-4th-edi)
[4](https://stackoverflow.com/questions/47995901/implementing-bellman-ford-in-python "Question score (upvotes - downvotes)")
[Implementing Bellman-Ford in python](https://stackoverflow.com/questions/47995901/implementing-bellman-ford-in-python)
[3](https://stackoverflow.com/questions/53454427/yens-bannister-eppstein-optimization-of-bellman-ford-algorithm "Question score (upvotes - downvotes)")
[Yen's & Bannister-Eppstein optimization of Bellman-Ford algorithm](https://stackoverflow.com/questions/53454427/yens-bannister-eppstein-optimization-of-bellman-ford-algorithm)
[0](https://stackoverflow.com/questions/65097691/reveresed-bellman-ford-algorithm "Question score (upvotes - downvotes)")
[Reveresed Bellman Ford algorithm](https://stackoverflow.com/questions/65097691/reveresed-bellman-ford-algorithm)
[0](https://stackoverflow.com/questions/66949385/is-my-implement-of-the-correctness-of-bellman-ford-algorithm-wrong "Question score (upvotes - downvotes)")
[Is my implement of the correctness of Bellman-Ford algorithm wrong?](https://stackoverflow.com/questions/66949385/is-my-implement-of-the-correctness-of-bellman-ford-algorithm-wrong)
#### [Hot Network Questions](https://stackexchange.com/questions?tab=hot)
- ["The eggs are the cheapest item/itemsā Singular or plural?](https://english.stackexchange.com/questions/639205/the-eggs-are-the-cheapest-item-items-singular-or-plural)
- [Should dashes be written before or after symbol in RTL text?](https://linguistics.stackexchange.com/questions/51620/should-dashes-be-written-before-or-after-symbol-in-rtl-text)
- [What dedicated syntax has been used for \`fold\`/\`reduce\`?](https://langdev.stackexchange.com/questions/4737/what-dedicated-syntax-has-been-used-for-fold-reduce)
- [Choosing splines terms for continuous predictors](https://stats.stackexchange.com/questions/675152/choosing-splines-terms-for-continuous-predictors)
- [May a retiree claim affiliation with former, long-term employer?](https://academia.stackexchange.com/questions/226173/may-a-retiree-claim-affiliation-with-former-long-term-employer)
- [Significance of reference levels of factors in multiple regression](https://stats.stackexchange.com/questions/675141/significance-of-reference-levels-of-factors-in-multiple-regression)
- [Mixing masculine and feminine forms in "bel et bonne"](https://french.stackexchange.com/questions/58781/mixing-masculine-and-feminine-forms-in-bel-et-bonne)
- [Do we see (many) duplicate objects / galaxies?](https://astronomy.stackexchange.com/questions/62262/do-we-see-many-duplicate-objects-galaxies)
- [Resetting Ubuntu using \`dconf reset -f /\` to default deletes what exactly?](https://askubuntu.com/questions/1564759/resetting-ubuntu-using-dconf-reset-f-to-default-deletes-what-exactly)
- [List of Kangxi radicals (åŗ·ēéØé¦)](https://codegolf.stackexchange.com/questions/287532/list-of-kangxi-radicals-%E5%BA%B7%E7%86%99%E9%83%A8%E9%A6%96)
- [What are migratory legends?](https://literature.stackexchange.com/questions/31782/what-are-migratory-legends)
- [Why does "Set Material" node block Render Passes? Eevee](https://blender.stackexchange.com/questions/345638/why-does-set-material-node-block-render-passes-eevee)
- [Why is SEPIC converter named so? Is it a misnomer?](https://electronics.stackexchange.com/questions/766875/why-is-sepic-converter-named-so-is-it-a-misnomer)
- [Getting size of overview in QGIS Print layout](https://gis.stackexchange.com/questions/500242/getting-size-of-overview-in-qgis-print-layout)
- [Faster way to list all files in directory?](https://stackoverflow.com/questions/79905435/faster-way-to-list-all-files-in-directory)
- [Definite Integral of square root of a quadratic function](https://mathematica.stackexchange.com/questions/319005/definite-integral-of-square-root-of-a-quadratic-function)
- [CLI Task Tracker](https://codereview.stackexchange.com/questions/301573/cli-task-tracker)
- [Count spaces in LaTeX](https://tex.stackexchange.com/questions/760770/count-spaces-in-latex)
- [Why did the Adjutant-General's Office create "A list of Christian names" and similar texts in the 1920s?](https://history.stackexchange.com/questions/79917/why-did-the-adjutant-generals-office-create-a-list-of-christian-names-and-sim)
- [Perlin noise implementation](https://codereview.stackexchange.com/questions/301577/perlin-noise-implementation)
- [Why do certain random permutation statistics not depend on the size of the underlying set?](https://math.stackexchange.com/questions/5128372/why-do-certain-random-permutation-statistics-not-depend-on-the-size-of-the-under)
- [Blender rigging Z fold box](https://blender.stackexchange.com/questions/345630/blender-rigging-z-fold-box)
- [Explain the Hidden Formula](https://puzzling.stackexchange.com/questions/137387/explain-the-hidden-formula)
- [Dialog file selector for specific types of files](https://askubuntu.com/questions/1564774/dialog-file-selector-for-specific-types-of-files)
[more hot questions](https://stackoverflow.com/questions/41517416/implementation-of-bellman-ford-algorithm-in-python)
[Question feed](https://stackoverflow.com/feeds/question/41517416 "Feed of this question and its answers")
# Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-py

##### [Stack Overflow](https://stackoverflow.com/)
- [Questions](https://stackoverflow.com/questions)
- [Help](https://stackoverflow.com/help)
- [Chat](https://chat.stackoverflow.com/?tab=explore)
##### [Business](https://stackoverflow.co/)
- [Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=teams)
- [Stack Data Licensing](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=data-licensing)
- [Stack Ads](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=advertising)
##### [Company](https://stackoverflow.co/)
- [About](https://stackoverflow.co/)
- [Press](https://stackoverflow.co/company/press/)
- [Work Here](https://stackoverflow.co/company/work-here/)
- [Legal](https://stackoverflow.com/legal)
- [Privacy Policy](https://stackoverflow.com/legal/privacy-policy)
- [Terms of Service](https://stackoverflow.com/legal/terms-of-service/public)
- [Contact Us](https://stackoverflow.com/contact)
- Cookie Settings
- [Cookie Policy](https://policies.stackoverflow.co/stack-overflow/cookie-policy)
##### [Stack Exchange Network](https://stackexchange.com/)
- [Technology](https://stackexchange.com/sites#technology)
- [Culture & recreation](https://stackexchange.com/sites#culturerecreation)
- [Life & arts](https://stackexchange.com/sites#lifearts)
- [Science](https://stackexchange.com/sites#science)
- [Professional](https://stackexchange.com/sites#professional)
- [Business](https://stackexchange.com/sites#business)
- [API](https://api.stackexchange.com/)
- [Data](https://data.stackexchange.com/)
- [Blog](https://stackoverflow.blog/?blb=1)
- [Facebook](https://www.facebook.com/officialstackoverflow/)
- [Twitter](https://twitter.com/stackoverflow)
- [LinkedIn](https://linkedin.com/company/stack-overflow)
- [Instagram](https://www.instagram.com/thestackoverflow)
Site design / logo Ā© 2026 Stack Exchange Inc; user contributions licensed under [CC BY-SA](https://stackoverflow.com/help/licensing) . rev 2026.3.12.40898 |
| Readable Markdown | This code does not work for graphs that are not connected eg it gives 1 for the following case which is correct:
```
edges = []
edges.append([0, 1, 5])
edges.append([2, 3, -5])
edges.append([3, 4, -6])
edges.append([4, 2, -5])
edges.append([1, 2, 5])
print(bellmanFord(5, edges))
```
Link to demo : <http://ideone.com/j8XAs3>
and when we remove the edge 1 -\> 2 it gives it gives 0, even though the graph has a negative cycle (2 -\> 3 -\> 4 -\> 2) :
```
edges = []
edges.append([0, 1, 5])
edges.append([2, 3, -5])
edges.append([3, 4, -6])
edges.append([4, 2, -5])
print(bellmanFord(5, edges))
```
Link to demo : <http://ideone.com/N4Bljk>
***
EDIT:
As you said that the test case \#12 passed after you used every vertex as source, I do believe that the graph is not connected, the problem is that the time complexity of the solution has increased it is now `O(n*n*m)` i.e about 10^11 operations that is certain to time out.
So you can modify the algorithm in the following way :
1\) Find all the connected components and separate out the vertices and edges for that component and create a new graphs with those vertices and edges
2\) Suppose you have k new graphs now, run Bellman Ford on each of them.
Also you are using the word "strongly connected" in the wrong way, a directed graph is strongly connected if there is a path from every vertex to every other possible vertex.
I saw the question that you are referring to, I assume it is "Problem: Detecting Anomalies in Currency Exchange Rates" if I am right regarding the question then the example given in the question contradicts the fact that it is strongly connected as there is no way to reach the vertex 4, the graph however is connected.
Example in the question :
```
4 4
1 2 -5
4 1 2
2 3 2
3 1 1
```
Do let me know if it is not the question you are referring to, or if you have some other doubts. |
| Shard | 169 (laksa) |
| Root Hash | 714406497480128969 |
| Unparsed URL | com,stackoverflow!/questions/41517416/implementation-of-bellman-ford-algorithm-in-python s443 |