Skip to content

Commit ab297d3

Browse files
Snapshot graph nodes when checking bipartiteness
1 parent 1b8189b commit ab297d3

1 file changed

Lines changed: 10 additions & 12 deletions

File tree

graphs/check_bipatrite.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
from collections import defaultdict, deque
2+
from collections.abc import Iterable, Mapping
23

34

4-
def is_bipartite_dfs(graph: defaultdict[int, list[int]]) -> bool:
5+
Graph = Mapping[int, Iterable[int]]
6+
7+
8+
def is_bipartite_dfs(graph: Graph) -> bool:
59
"""
610
Check if a graph is bipartite using depth-first search (DFS).
711
@@ -15,11 +19,8 @@ def is_bipartite_dfs(graph: defaultdict[int, list[int]]) -> bool:
1519
vertices within the same set are connected by an edge.
1620
1721
Examples:
18-
# FIXME: This test should pass.
1922
>>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]}))
20-
Traceback (most recent call last):
21-
...
22-
RuntimeError: dictionary changed size during iteration
23+
True
2324
>>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 1]}))
2425
False
2526
>>> is_bipartite_dfs({})
@@ -84,13 +85,13 @@ def depth_first_search(node: int, color: int) -> bool:
8485
return visited[node] == color
8586

8687
visited: defaultdict[int, int] = defaultdict(lambda: -1)
87-
for node in graph:
88+
for node in list(graph):
8889
if visited[node] == -1 and not depth_first_search(node, 0):
8990
return False
9091
return True
9192

9293

93-
def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool:
94+
def is_bipartite_bfs(graph: Graph) -> bool:
9495
"""
9596
Check if a graph is bipartite using a breadth-first search (BFS).
9697
@@ -104,11 +105,8 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool:
104105
vertices within the same set are connected by an edge.
105106
106107
Examples:
107-
# FIXME: This test should pass.
108108
>>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]}))
109-
Traceback (most recent call last):
110-
...
111-
RuntimeError: dictionary changed size during iteration
109+
True
112110
>>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 2], 2: [0, 1]}))
113111
False
114112
>>> is_bipartite_bfs({})
@@ -153,7 +151,7 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool:
153151
KeyError: 'b'
154152
"""
155153
visited: defaultdict[int, int] = defaultdict(lambda: -1)
156-
for node in graph:
154+
for node in list(graph):
157155
if visited[node] == -1:
158156
queue: deque[int] = deque()
159157
queue.append(node)

0 commit comments

Comments
 (0)