MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / is_bipartite_dfs

Function is_bipartite_dfs

graphs/check_bipatrite.py:4–81  ·  view source on GitHub ↗

Check if a graph is bipartite using depth-first search (DFS). Args: `graph`: Adjacency list representing the graph. Returns: ``True`` if bipartite, ``False`` otherwise. Checks if the graph can be divided into two sets of vertices, such that no two vertices wit

(graph: dict[int, list[int]])

Source from the content-addressed store, hash-verified

2
3
4def is_bipartite_dfs(graph: dict[int, list[int]]) -> bool:
5 """
6 Check if a graph is bipartite using depth-first search (DFS).
7
8 Args:
9 `graph`: Adjacency list representing the graph.
10
11 Returns:
12 ``True`` if bipartite, ``False`` otherwise.
13
14 Checks if the graph can be divided into two sets of vertices, such that no two
15 vertices within the same set are connected by an edge.
16
17 Examples:
18
19 >>> is_bipartite_dfs({0: [1, 2], 1: [0, 3], 2: [0, 4]})
20 True
21 >>> is_bipartite_dfs({0: [1, 2], 1: [0, 3], 2: [0, 1]})
22 False
23 >>> is_bipartite_dfs({})
24 True
25 >>> is_bipartite_dfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]})
26 True
27 >>> is_bipartite_dfs({0: [1, 2, 3], 1: [0, 2], 2: [0, 1, 3], 3: [0, 2]})
28 False
29 >>> is_bipartite_dfs({0: [4], 1: [], 2: [4], 3: [4], 4: [0, 2, 3]})
30 True
31 >>> is_bipartite_dfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: [0]})
32 False
33 >>> is_bipartite_dfs({7: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: [0]})
34 False
35
36 >>> # FIXME: This test should fails with KeyError: 4.
37 >>> is_bipartite_dfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 9: [0]})
38 False
39 >>> is_bipartite_dfs({0: [-1, 3], 1: [0, -2]})
40 False
41 >>> is_bipartite_dfs({-1: [0, 2], 0: [-1, 1], 1: [0, 2], 2: [-1, 1]})
42 True
43 >>> is_bipartite_dfs({0.9: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]})
44 True
45
46 >>> # FIXME: This test should fails with
47 >>> # TypeError: list indices must be integers or...
48 >>> is_bipartite_dfs({0: [1.0, 3.0], 1.0: [0, 2.0], 2.0: [1.0, 3.0], 3.0: [0, 2.0]})
49 True
50 >>> is_bipartite_dfs({"a": [1, 3], "b": [0, 2], "c": [1, 3], "d": [0, 2]})
51 True
52 >>> is_bipartite_dfs({0: ["b", "d"], 1: ["a", "c"], 2: ["b", "d"], 3: ["a", "c"]})
53 True
54 """
55
56 def depth_first_search(node: int, color: int) -> bool:
57 """
58 Perform Depth-First Search (DFS) on the graph starting from a node.
59
60 Args:
61 node: The current node being visited.

Callers

nothing calls this directly

Calls 1

depth_first_searchFunction · 0.70

Tested by

no test coverage detected