Add lab/quiz 5 work
This commit is contained in:
parent
a0f031f727
commit
50ebe0092c
BIN
Labs/5/5.odt
Normal file
BIN
Labs/5/5.odt
Normal file
Binary file not shown.
BIN
Labs/5/5.pdf
Normal file
BIN
Labs/5/5.pdf
Normal file
Binary file not shown.
BIN
Labs/5/5.png
Normal file
BIN
Labs/5/5.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 45 KiB |
53
Labs/5/5.py
Normal file
53
Labs/5/5.py
Normal file
@ -0,0 +1,53 @@
|
||||
import heapq
|
||||
|
||||
def dijkstra_verbose(graph, start):
|
||||
distances = {node: float('inf') for node in graph}
|
||||
distances[start] = 0
|
||||
pq = [(0, start)]
|
||||
step = 0
|
||||
|
||||
print(f"\n--- Dijkstra's Algorithm from Node {start} ---\n")
|
||||
print(f"Initial distances: {distances}")
|
||||
|
||||
while pq:
|
||||
current_distance, current_node = heapq.heappop(pq)
|
||||
print(f"\nStep {step}: Visiting node {current_node} with current distance {current_distance}")
|
||||
|
||||
if current_distance > distances[current_node]:
|
||||
print("\tSkipping since a shorter path is already found.")
|
||||
continue
|
||||
|
||||
for neighbor, weight in graph[current_node].items():
|
||||
distance = current_distance + weight
|
||||
if distance < distances[neighbor]:
|
||||
old_distance = distances[neighbor]
|
||||
distances[neighbor] = distance
|
||||
heapq.heappush(pq, (distance, neighbor))
|
||||
print(f"\tUpdating distance to node {neighbor}: {old_distance} -> {distance}")
|
||||
else:
|
||||
print(f"\tNo update required for node {neighbor} (current: {distances[neighbor]}, new: {distance})")
|
||||
|
||||
print(f"Distances after step {step}: {distances}")
|
||||
step += 1
|
||||
|
||||
print(f"\nFinal shortest distances from node {start}: {distances}")
|
||||
return distances
|
||||
|
||||
# Compute SSSPT for each node and print the steps
|
||||
graph = {
|
||||
0: {1: 3, 2: 1},
|
||||
1: {3: 2},
|
||||
2: {1: 1, 4: 5, 5: 5},
|
||||
3: {2: 4, 4: 3},
|
||||
4: {5: 1, 6: 3},
|
||||
5: {6: 1, 7: 4},
|
||||
6: {7: 1},
|
||||
7: {}
|
||||
}
|
||||
|
||||
#Compute SSSPT for each node and print the steps
|
||||
#for node in graph:
|
||||
# dijkstra_verbose(graph, node)
|
||||
|
||||
# Compute SSSPT for a specific node and print the steps
|
||||
dijkstra_verbose(graph, 0)
|
BIN
Labs/5/5.xcf
Normal file
BIN
Labs/5/5.xcf
Normal file
Binary file not shown.
BIN
Labs/5/Q1.png
Normal file
BIN
Labs/5/Q1.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 35 KiB |
BIN
Labs/5/Q4.png
Normal file
BIN
Labs/5/Q4.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 82 KiB |
Loading…
x
Reference in New Issue
Block a user