Skip to content

Commit 86baec0

Browse files
authored
Fix mypy errors at bfs_zero_one_shortest_path (TheAlgorithms#4521)
1 parent 62d4418 commit 86baec0

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

graphs/bfs_zero_one_shortest_path.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from collections import deque
2+
from collections.abc import Iterator
23
from dataclasses import dataclass
3-
from typing import Iterator, List
4+
from typing import Optional, Union
45

56
"""
67
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
@@ -21,7 +22,7 @@ class AdjacencyList:
2122
"""Graph adjacency list."""
2223

2324
def __init__(self, size: int):
24-
self._graph: List[List[Edge]] = [[] for _ in range(size)]
25+
self._graph: list[list[Edge]] = [[] for _ in range(size)]
2526
self._size = size
2627

2728
def __getitem__(self, vertex: int) -> Iterator[Edge]:
@@ -58,7 +59,7 @@ def add_edge(self, from_vertex: int, to_vertex: int, weight: int):
5859

5960
self._graph[from_vertex].append(Edge(to_vertex, weight))
6061

61-
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int:
62+
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> Optional[int]:
6263
"""
6364
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
6465
1 1 1
@@ -106,18 +107,21 @@ def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int:
106107
ValueError: No path from start_vertex to finish_vertex.
107108
"""
108109
queue = deque([start_vertex])
109-
distances = [None for i in range(self.size)]
110+
distances: list[Union[int, None]] = [None] * self.size
110111
distances[start_vertex] = 0
111112

112113
while queue:
113114
current_vertex = queue.popleft()
114115
current_distance = distances[current_vertex]
116+
if current_distance is None:
117+
continue
115118

116119
for edge in self[current_vertex]:
117120
new_distance = current_distance + edge.weight
121+
dest_vertex_distance = distances[edge.destination_vertex]
118122
if (
119-
distances[edge.destination_vertex] is not None
120-
and new_distance >= distances[edge.destination_vertex]
123+
isinstance(dest_vertex_distance, int)
124+
and new_distance >= dest_vertex_distance
121125
):
122126
continue
123127
distances[edge.destination_vertex] = new_distance

0 commit comments

Comments
 (0)