From dcb5d6a6e7673b8c195f7fd22f71111dd6d3a0ac Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 22 Dec 2022 08:37:26 +0900 Subject: [PATCH] Add add-piedroconti --- algorithms/Python/README.md | 1 + algorithms/Python/graphs/dijkstra.py | 59 ++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 algorithms/Python/graphs/dijkstra.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 56e61288..0ddadead 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -80,6 +80,7 @@ - [Simple Graph](graphs/graph.py) - [BFS SEQUENCE](graphs/bfs-sequence.py) - [Depth First Search](graphs/depth-first-search.py) + [Dijkstra's algorithm](graphs/dijkstra.py) ## Trees - [Binary Tree](trees/binary_tree.py) diff --git a/algorithms/Python/graphs/dijkstra.py b/algorithms/Python/graphs/dijkstra.py new file mode 100644 index 00000000..c6709460 --- /dev/null +++ b/algorithms/Python/graphs/dijkstra.py @@ -0,0 +1,59 @@ +import heapq +INF = 10**9 + +# make graph, set start node +V, E = map(int, input().split()) +graph = [[]for _ in range(V)] # adjlist +start = int(input()) + +# make edges +for _ in range(E): + u, v, w = map(int, input().split()) + graph[u].append((v, w)) + +# make list of distance from start to des, visit status, priority queue +dist = [INF] * (V) +visit = [False] * (V) +PQ = [(0, start)] # cost, vertice + +# djikstra algorithm +while PQ: + cost, node = heapq.heappop(PQ) + if visit[node]: continue + + visit[node] = True + dist[node] = cost + for v, w in graph[node]: + alt = cost + w + heapq.heappush(PQ, (alt, v)) + +""" +SAMPLE INPUT AND OUTPUT + ___________________________ + Input: + __________ + + 5 6 + + 0 + + 4 0 1 + 0 1 2 + 0 2 3 + 1 2 4 + 1 3 5 + 2 3 6 + + Output: + ___________ + Distances from start node 0 + 0 + 2 + 3 + 7 + INF +""" + +for i in dist: + if i == INF: print("INF") + else: print(i) \ No newline at end of file