Ishaan28malik / Hacktoberfest-2023

Make this Hacktoberfest a learning period and contribute to Great Open Source Projects.
MIT License
550 stars 1.71k forks source link

Update dijkstra.py #1977

Open Devika-H opened 10 months ago

Devika-H commented 10 months ago

Here's a Python implementation of Dijkstra's algorithm that uses a priority queue to improve the efficiency of finding the minimum distance vertex. This implementation is more efficient than the one which follows modern Python practices.

In this improved code:

  1. We use a priority queue implemented with Python's heapq module to efficiently extract the vertex with the minimum distance.

  2. The add_edge method is used to add edges to the graph. Each edge is represented as a tuple (v, w), where v is the adjacent vertex, and w is the edge weight.

  3. The dijkstra method computes the shortest path from the source vertex to all other vertices using Dijkstra's algorithm.

  4. The print_solution method is used to print the shortest distances from the source vertex to all other vertices.

This code is more efficient and follows better Python coding practices for Dijkstra's algorithm.