Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the program to check Bipartite Graph #1095

Merged
merged 2 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -102,6 +102,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
Loading