From 8b59de8f14369fddf04ca97e07a49414da46a729 Mon Sep 17 00:00:00 2001 From: Andreas Gemsa Date: Tue, 21 May 2024 21:32:00 +0200 Subject: [PATCH] improved BFS --- graph/algorithms.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/graph/algorithms.py b/graph/algorithms.py index 5a8e26b..bb2e652 100644 --- a/graph/algorithms.py +++ b/graph/algorithms.py @@ -4,18 +4,20 @@ from utils import timer from graph.graph import Graph -from typing import Set +from typing import Deque, Set def BFS(graph: Graph, s: int) -> Set[int]: - seen_nodes = {s} - unvisited_nodes = deque([s]) - - while len(unvisited_nodes) > 0: - node_id = unvisited_nodes.popleft() - unseen_nodes = list( - filter(lambda n: n not in seen_nodes, graph.all_neighbors(node_id)) - ) + seen_nodes: Set[int] = {s} + unvisited_nodes: Deque[int] = deque([s]) + + while unvisited_nodes: + current_node = unvisited_nodes.popleft() + unseen_nodes = [ + neighbor + for neighbor in graph.all_neighbors(current_node) + if neighbor not in seen_nodes + ] seen_nodes.update(unseen_nodes) unvisited_nodes.extend(unseen_nodes)