How to Check Bipartite Graph Using BFS in Python

In this tutorial, we will learn "How to Check if a Graph is Bipartite using BFS in Python". The main objective is to understand and implement a method for checking whether a graph is bipartite using Breadth-First Search (BFS). This guide will walk you step by step through the process, making it easier to follow and apply. By the end of this tutorial, you will have a solid understanding of how BFS works in Python for this problem, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of implementing a bipartite graph check using BFS. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of checking a bipartite graph using BFS in Python.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. from collections import deque
  2.  
  3.  
  4. def is_bipartite(graph, start):
  5.     color = {}
  6.  
  7.     queue = deque([start])
  8.     color[start] = 0  # Assign first color
  9.  
  10.     while queue:
  11.         node = queue.popleft()
  12.  
  13.         for neighbor in graph[node]:
  14.             if neighbor not in color:
  15.                 color[neighbor] = 1 - color[node]  # Alternate color
  16.                 queue.append(neighbor)
  17.             elif color[neighbor] == color[node]:
  18.                 return False  # Same color conflict → not bipartite
  19.  
  20.     return True
  21.  
  22.  
  23. # MAIN PROGRAM
  24. while True:
  25.     print("\n========== Check Bipartite Graph Using BFS ==========\n")
  26.  
  27.     graph = {}
  28.  
  29.     # Input number of vertices
  30.     try:
  31.         n = int(input("Enter number of vertices: "))
  32.     except ValueError:
  33.         print("Invalid input.")
  34.         continue
  35.  
  36.     # Input adjacency list
  37.     print("\nEnter adjacency list (space-separated neighbors):")
  38.     for i in range(n):
  39.         try:
  40.             neighbors = list(map(int, input(f"Vertex {i}: ").split()))
  41.             graph[i] = neighbors
  42.         except ValueError:
  43.             print("Invalid input.")
  44.             break
  45.  
  46.     # Check bipartite
  47.     result = True
  48.     visited = set()
  49.  
  50.     for node in graph:
  51.         if node not in visited:
  52.             if not is_bipartite(graph, node):
  53.                 result = False
  54.                 break
  55.             visited.update(graph.keys())
  56.  
  57.     # Output result
  58.     if result:
  59.         print("\nGraph is Bipartite ✅")
  60.     else:
  61.         print("\nGraph is NOT Bipartite ❌")
  62.  
  63.     # Try Again Option
  64.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  65.     if opt == "no":
  66.         print("Exiting program...")
  67.         break
  68.     elif opt != "yes":
  69.         print("Invalid choice. Exiting program...")
  70.         break

This Python program checks whether a graph is bipartite using Breadth-First Search (BFS). It defines an `is_bipartite` function that uses a queue to traverse the graph and assigns alternating colors to adjacent vertices, ensuring no two connected vertices share the same color. The user inputs the number of vertices and their adjacency lists, and the program evaluates each connected component of the graph. If a conflict in coloring is found, the graph is not bipartite; otherwise, it is bipartite. The program runs interactively, allowing users to test multiple graphs until they choose to exit.

Output:

There you have it we successfully created How to Check Bipartite Graph Using BFS in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials