From ab09aa5269d64c93625757936f205bc05de125f0 Mon Sep 17 00:00:00 2001 From: onyx-and-iris Date: Mon, 19 Feb 2024 00:03:44 +0000 Subject: [PATCH] add visited set --- chapter9/with_heap/ex171a.py | 5 +++++ chapter9/with_heap/ex171b.py | 5 +++++ chapter9/with_heap/ex171c.py | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/chapter9/with_heap/ex171a.py b/chapter9/with_heap/ex171a.py index 36b2f03..7c8ba56 100644 --- a/chapter9/with_heap/ex171a.py +++ b/chapter9/with_heap/ex171a.py @@ -20,10 +20,15 @@ def dijkstra(graph, node): costs[node] = 0 parents = {node: None for node in graph} queue = [(0, node)] + visited = set() while queue: current_cost, current_node = heapq.heappop(queue) + if current_node in visited: + continue + logger.debug(f"node {current_node} with cost {current_cost} popped from pqueue") + visited.add(current_node) for next_node, weight in graph[current_node].items(): new_cost = current_cost + weight diff --git a/chapter9/with_heap/ex171b.py b/chapter9/with_heap/ex171b.py index e6551a6..66db310 100644 --- a/chapter9/with_heap/ex171b.py +++ b/chapter9/with_heap/ex171b.py @@ -19,10 +19,15 @@ def dijkstra(graph, node): costs[node] = 0 parents = {node: None for node in graph} queue = [(0, node)] + visited = set() while queue: current_cost, current_node = heapq.heappop(queue) + if current_node in visited: + continue + logger.debug(f"node {current_node} with cost {current_cost} popped from pqueue") + visited.add(current_node) for next_node, weight in graph[current_node].items(): new_cost = current_cost + weight diff --git a/chapter9/with_heap/ex171c.py b/chapter9/with_heap/ex171c.py index 00e17ac..6a37bd4 100644 --- a/chapter9/with_heap/ex171c.py +++ b/chapter9/with_heap/ex171c.py @@ -19,10 +19,15 @@ def dijkstra(graph, node): costs[node] = 0 parents = {node: None for node in graph} queue = [(0, node)] + visited = set() while queue: current_cost, current_node = heapq.heappop(queue) + if current_node in visited: + continue + logger.debug(f"node {current_node} with cost {current_cost} popped from pqueue") + visited.add(current_node) for next_node, weight in graph[current_node].items(): new_cost = current_cost + weight