Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
shivaparihar6119 committed Oct 19, 2023
1 parent 3388864 commit 6a2a920
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 102 deletions.
110 changes: 110 additions & 0 deletions graphs/check_bipartite_graph_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@

''' Check whether Graph is Bipartite or Not using BFS
https://www.geeksforgeeks.org/bipartite-graph/
Args:
graph: An adjacency list representing the graph.
Returns:
True if there's no edge that connects vertices of the same set, False otherwise.
Examples:
>>> is_bipartite(
... defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4], 3: [1], 4: [2]})
... )
False
>>> is_bipartite(defaultdict(list, {0: [1, 2], 1: [0, 2], 2: [0, 1]}))
True'''
from queue import Queue


def check_bipartite(graph):
queue = Queue()
visited = [False] * len(graph)
color = [-1] * len(graph)

def bfs():
while not queue.empty():
u = queue.get()
visited[u] = True

for neighbour in graph[u]:
if neighbour == u:
return False

if color[neighbour] == -1:
color[neighbour] = 1 - color[u]
queue.put(neighbour)

elif color[neighbour] == color[u]:
return False

return True

for i in range(len(graph)):
if not visited[i]:
queue.put(i)
color[i] = 0
if bfs() is False:
return False

return True


if __name__ == "__main__":
# Adjacency List of graph
print(check_bipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))


from collections import defaultdict


def is_bipartite(graph: defaultdict[int, list[int]]) -> bool:
"""
Check whether a graph is Bipartite or not using Depth-First Search (DFS).
https://www.geeksforgeeks.org/check-if-a-given-graph-is-bipartite-using-dfs/
Args:
graph: An adjacency list representing the graph.
Returns:
True if there's no edge that connects vertices of the same set, False otherwise.
Examples:
>>> is_bipartite(
... defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4], 3: [1], 4: [2]})
... )
False
>>> is_bipartite(defaultdict(list, {0: [1, 2], 1: [0, 2], 2: [0, 1]}))
True
"""

def depth_first_search(node: int, color: int) -> bool:
visited[node] = color
return any(
visited[neighbour] == color
or (
visited[neighbour] == -1
and not depth_first_search(neighbour, 1 - color)
)
for neighbour in graph[node]
)

visited: defaultdict[int, int] = defaultdict(lambda: -1)

return all(
not (visited[node] == -1 and not depth_first_search(node, 0)) for node in graph
)


if __name__ == "__main__":
import doctest

result = doctest.testmod()

if result.failed:
print(f"{result.failed} test(s) failed.")
else:
print("All tests passed!")

47 changes: 0 additions & 47 deletions graphs/check_bipartite_graph_bfs.py

This file was deleted.

55 changes: 0 additions & 55 deletions graphs/check_bipartite_graph_dfs.py

This file was deleted.

0 comments on commit 6a2a920

Please sign in to comment.