Skip to content

Commit

Permalink
improved BFS
Browse files Browse the repository at this point in the history
  • Loading branch information
AndGem committed May 21, 2024
1 parent 0cba6aa commit 8b59de8
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions graph/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 8b59de8

Please sign in to comment.