Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bd3c3a2

Browse files
Added Dijkstra's Algorithmn
1 parent adfa11f commit bd3c3a2

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

‎D/Dijkstra's Algorithm/dijkstra.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import heapq
2+
3+
def dijkstra(graph, start):
4+
# Initialize distances and predecessors
5+
distances = {vertex: float('infinity') for vertex in graph}
6+
distances[start] = 0
7+
predecessors = {}
8+
9+
# Priority queue to keep track of vertices to visit
10+
vertices_to_visit = [(0, start)]
11+
12+
while vertices_to_visit:
13+
current_distance, current_vertex = heapq.heappop(vertices_to_visit)
14+
15+
# If the current distance is larger than the stored distance, skip it
16+
if current_distance > distances[current_vertex]:
17+
continue
18+
19+
for neighbor, weight in graph[current_vertex].items():
20+
distance = current_distance + weight
21+
22+
if distance < distances[neighbor]:
23+
distances[neighbor] = distance
24+
predecessors[neighbor] = current_vertex
25+
heapq.heappush(vertices_to_visit, (distance, neighbor))
26+
27+
return distances, predecessors
28+
29+
# Example graph as an adjacency dictionary
30+
graph = {
31+
'A': {'B': 1, 'C': 4},
32+
'B': {'A': 1, 'C': 2, 'D': 5},
33+
'C': {'A': 4, 'B': 2, 'D': 1},
34+
'D': {'B': 5, 'C': 1}
35+
}
36+
37+
start_vertex = 'A'
38+
distances, predecessors = dijkstra(graph, start_vertex)
39+
40+
# Print the shortest distances and paths from the start vertex
41+
for vertex, distance in distances.items():
42+
path = [vertex]
43+
while vertex != start_vertex:
44+
vertex = predecessors[vertex]
45+
path.insert(0, vertex)
46+
print(f'Shortest path to {vertex}: {path}, Distance: {distance}')

‎D/Dijkstra's Algorithm/readme.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Dijkstra's Algorithm in Python
2+
3+
This Python program implements Dijkstra's Algorithm to find the shortest path from a specified source vertex to all other vertices in a weighted graph. Dijkstra's Algorithm is a fundamental algorithm for finding the shortest paths in a graph, and it is commonly used in various applications, such as routing and network optimization.
4+
5+
## Table of Contents
6+
7+
- [Requirements](#requirements)
8+
- [Algorithm Overview](#algorithm-overview)
9+
- [Contributing](#contributing)
10+
11+
## Requirements
12+
13+
To run this program, you need:
14+
15+
- Python 3.x
16+
17+
No additional external libraries are required.
18+
19+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /