FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/graph/bellman_ford.py at master · ivan1911/algorithms-python · GitHub
ivan1911
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
graph
/
bellman_ford.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
48 lines (41 loc) · 1.45 KB
Breadcrumbs
algorithms-python
/
algorithms
/
graph
/
bellman_ford.py
Copy path
File metadata and controls
48 lines (41 loc) · 1.45 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Determination of single-source shortest-path.
"""
def
bellman_ford
(
graph
,
source
):
"""
This Bellman-Ford Code is for determination whether we can get
shortest path from given graph or not for single-source shortest-paths problem.
In other words, if given graph has any negative-weight cycle that is reachable
from the source, then it will give answer False for "no solution exits".
For argument graph, it should be a dictionary type
such as
graph = {
'a': {'b': 6, 'e': 7},
'b': {'c': 5, 'd': -4, 'e': 8},
'c': {'b': -2},
'd': {'a': 2, 'c': 7},
'e': {'b': -3}
}
"""
weight
=
{}
pre_node
=
{}
initialize_single_source
(
graph
,
source
,
weight
,
pre_node
)
for
_
in
range
(
1
,
len
(
graph
)):
for
node
in
graph
:
for
adjacent
in
graph
[
node
]:
if
weight
[
adjacent
]
>
weight
[
node
]
+
graph
[
node
][
adjacent
]:
weight
[
adjacent
]
=
weight
[
node
]
+
graph
[
node
][
adjacent
]
pre_node
[
adjacent
]
=
node
for
node
in
graph
:
for
adjacent
in
graph
[
node
]:
if
weight
[
adjacent
]
>
weight
[
node
]
+
graph
[
node
][
adjacent
]:
return
False
return
True
def
initialize_single_source
(
graph
,
source
,
weight
,
pre_node
):
"""
Initialize data structures for Bellman-Ford algorithm.
"""
for
node
in
graph
:
weight
[
node
]
=
float
(
'inf'
)
pre_node
[
node
]
=
None
weight
[
source
]
=
0
Back
|
FazBrowse Home
|
New Git URL