Skip to content

feat: replace Bellman Ford Algorithm with queue version #629

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 11, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 22 additions & 15 deletions pydatastructs/graphs/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,7 @@ def shortest_paths(graph: Graph, algorithm: str,
The algorithm to be used. Currently, the following algorithms
are implemented,

'bellman_ford' -> Bellman-Ford algorithm as given in [1].
'bellman_ford' -> Bellman-Ford algorithm as given in [1]

'dijkstra' -> Dijkstra algorithm as given in [2].
source: str
Expand Down Expand Up @@ -754,27 +754,34 @@ def shortest_paths(graph: Graph, algorithm: str,
return getattr(algorithms, func)(graph, source, target)

def _bellman_ford_adjacency_list(graph: Graph, source: str, target: str) -> tuple:
distances, predecessor = {}, {}
distances, predecessor, visited, cnts = {}, {}, {}, {}

for v in graph.vertices:
distances[v] = float('inf')
predecessor[v] = None
visited[v] = False
cnts[v] = 0
distances[source] = 0
verticy_num = len(graph.vertices)

edges = graph.edge_weights.values()
for _ in range(len(graph.vertices) - 1):
for edge in edges:
u, v = edge.source.name, edge.target.name
w = edge.value
if distances[u] + edge.value < distances[v]:
distances[v] = distances[u] + w
predecessor[v] = u
que = Queue([source])

for edge in edges:
u, v = edge.source.name, edge.target.name
w = edge.value
if distances[u] + w < distances[v]:
raise ValueError("Graph contains a negative weight cycle.")
while que:
u = que.popleft()
visited[u] = False
neighbors = graph.neighbors(u)
for neighbor in neighbors:
v = neighbor.name
edge_str = u + '_' + v
if distances[u] != float('inf') and distances[u] + graph.edge_weights[edge_str].value < distances[v]:
distances[v] = distances[u] + graph.edge_weights[edge_str].value
predecessor[v] = u
cnts[v] = cnts[u] + 1
if cnts[v] >= verticy_num:
raise ValueError("Graph contains a negative weight cycle.")
if not visited[v]:
que.append(v)
visited[v] = True

if target != "":
return (distances[target], predecessor)
Expand Down
Loading