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

Rock-Leilani #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
34 changes: 30 additions & 4 deletions graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,38 @@

# Can be used for BFS
from collections import deque
from collections import deque
# Check whether Graph is Bipartite or Not using DFS

# A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex
# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V,
# or u belongs to V and v to U. We can also say that there is no edge that connects
# vertices of same set.

def possible_bipartition(dislikes):
""" Will return True or False if the given graph
can be bipartitioned without neighboring nodes put
into the same partition.
Time Complexity: ?
Space Complexity: ?
Time Complexity: O(n^2)
Space Complexity: O(n)
Comment on lines 12 to +17

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works, but the time complexity would be O(NE) because of the loops in lines 33-36.

This can be done using DFS in O(N + E) time, but you would need to modify your dfs helper function and how you handle the if statement in lines 30-31.

Otherwise nice dfs solution.

"""
pass
visited = [False] * len(dislikes)
color = [-1] * len(dislikes)

def dfs(v, c):
visited[v] = True
color[v] = c
for u in dislikes[v]:
if not visited[u]:
dfs(u, 1 - c)

for i in range(len(dislikes)):
if not visited[i]:
dfs(i, 0)

for i in range(len(dislikes)):
for j in dislikes[i]:
if color[i] == color[j]:
return False

return True