Skip to content

Commit

Permalink
Merge pull request UTSAVS26#1095 from shuvojitss/box-3
Browse files Browse the repository at this point in the history
Added the program to check Bipartite Graph
  • Loading branch information
UTSAVS26 authored Nov 5, 2024
2 parents 595fb66 + 4715d56 commit 7c2b34b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
43 changes: 43 additions & 0 deletions Algorithms_and_Data_Structures/Graph/Bipartite_Graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from collections import deque

def is_bipartite(adj_matrix, V):
# Initialize colors array with -1 (uncolored)
color = [-1] * V
# Process each component of the graph
for start in range(V):
# If the vertex is already colored, skip it
if color[start] != -1:
continue
# Start BFS from this node
q = deque([start])
color[start] = 0 # Color the starting vertex with 0
while q:
node = q.popleft()

for neighbor in range(V):
# Check if there's an edge between node and neighbor
if adj_matrix[node][neighbor] == 1:
# If the neighbor hasn't been colored, color it with the opposite color
if color[neighbor] == -1:
color[neighbor] = 1 - color[node]
q.append(neighbor)
# If the neighbor has the same color as the current node, the graph is not bipartite
elif color[neighbor] == color[node]:
return False
# If we successfully colored the graph, it's bipartite
return True

def main():
V = int(input("Enter the number of vertices: "))
adj_matrix = [[0] * V for _ in range(V)]
print("Enter the adjacency matrix:")
for i in range(V):
adj_matrix[i] = list(map(int, input().split()))

if is_bipartite(adj_matrix, V):
print("The graph is bipartite.")
else:
print("The graph is not bipartite.")

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
* [Unique-Paths](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/unique-paths.py)
* Graph
* [Adjacency Matrix](Algorithms_and_Data_Structures/Graph/Adjacency_Matrix.py)
* [Bipartite Graph](Algorithms_and_Data_Structures/Graph/Bipartite_Graph.py)
* [Graph Cloning](Algorithms_and_Data_Structures/Graph/Graph_Cloning.py)
* [Menu Driven Code Bfs Traversal](Algorithms_and_Data_Structures/Graph/Menu_driven_code_BFS_Traversal.py)
* [Menu Driven Code Dfs Traversal](Algorithms_and_Data_Structures/Graph/Menu_driven_code_DFS_Traversal.py)
Expand Down

0 comments on commit 7c2b34b

Please sign in to comment.