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
Show file tree
Hide file tree
Changes from 1 commit
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
34 changes: 34 additions & 0 deletions pydatastructs/graphs/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,8 @@ def shortest_paths(graph: Graph, algorithm: str,
'bellman_ford' -> Bellman-Ford algorithm as given in [1].

'dijkstra' -> Dijkstra algorithm as given in [2].

'queue_improved_bellman_ford' -> Queue Improved Bellman-Ford algorithm as given in [3].
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of a new one, let's just use Queues in Bellman Ford algorithm itself? Any specific for not doing so?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of a new one, let's just use Queues in Bellman Ford algorithm itself? Any specific for not doing so?

Adding modifications for original Bellman Ford algorithm? Like changing bellman_ford(graph: Graph, start: str, target: str) -> bellman_ford(graph: Graph, start: str, target: str, use_queue=False).

Or change original Bellman Ford to queue version.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If Queue version is always better then use Queue only. What's the difference between running times with and without queues?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The queue-based Bellman-Ford algorithm mainly reduces the number of times relaxation is needed. Especially on sparse graphs, it can significantly decrease the number of edges that need to be checked.

However, in the worst case, its time complexity is the same as that of the Bellman-Ford algorithm without using a queue.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On sparse graphs, the complexity is approximately $O(kE)$, where $k$ is the average number of times each vertex is enqueued.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So let's always use a queue. Change the original bellman ford implementation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. I'll make the modifications and change PR's name to "feat: replace Bellman Ford Algorithm with queue version"

source: str
The name of the source the node.
target: str
Expand Down Expand Up @@ -742,6 +744,7 @@ def shortest_paths(graph: Graph, algorithm: str,

.. [1] https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
.. [2] https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
.. [3] https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#Improvements
"""
raise_if_backend_is_not_python(
shortest_paths, kwargs.get('backend', Backend.PYTHON))
Expand Down Expand Up @@ -811,6 +814,37 @@ def _dijkstra_adjacency_list(graph: Graph, start: str, target: str):

_dijkstra_adjacency_matrix = _dijkstra_adjacency_list

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

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

que = Queue([source])

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
if not visited[v]:
que.append(v)
visited[v] = True

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

_queue_improved_bellman_ford_adjacency_matrix = _queue_improved_bellman_ford_adjacency_list

def all_pair_shortest_paths(graph: Graph, algorithm: str,
**kwargs) -> tuple:
"""
Expand Down
4 changes: 4 additions & 0 deletions pydatastructs/graphs/tests/test_algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,10 @@ def _test_shortest_paths_negative_edges(ds, algorithm):
_test_shortest_paths_negative_edges("Matrix", 'bellman_ford')
_test_shortest_paths_positive_edges("List", 'dijkstra')
_test_shortest_paths_positive_edges("Matrix", 'dijkstra')
_test_shortest_paths_positive_edges("List", 'queue_improved_bellman_ford')
_test_shortest_paths_positive_edges("Matrix", 'queue_improved_bellman_ford')
_test_shortest_paths_negative_edges("List", 'queue_improved_bellman_ford')
_test_shortest_paths_negative_edges("Matrix", 'queue_improved_bellman_ford')

def test_all_pair_shortest_paths():

Expand Down
Loading