Skip to content
Open
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
55 changes: 54 additions & 1 deletion graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,65 @@
# Can be used for BFS
from collections import deque




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: ?
Input: dislikes = [ [],
[2, 3], <-- node 1 neighbors
[1, 4], <-- node 2 neighbors
[1], <-- node 3 neighbors
[2] <-- node 4 nighbors
]
Outer for loop to loop through each node.
Inner loop Another loop keeps going as long as que is not empty
Inner most loop loops through the neighbors of current node
In order to be a bipartite graph, a node cannot be in same bucket as its neighbors
Return true if it is a bipartite graph
queues --> first one in first one out enque-->deque
"""
pass
if not dislikes:
return True

que = deque()
red = set()
green = set()

for node in range(len(dislikes)):
que.appendleft(node)

while que:
current = que.pop()
if current not in red and current not in green:
red.add(current)
elif current in green:
green.add(current)
Comment on lines +44 to +45

Choose a reason for hiding this comment

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

If current is in green add it to green? Is that what you wanted to do here?

else:
red.add(current)

for neighbor in dislikes[node]:
if neighbor not in red or green:

Choose a reason for hiding this comment

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

In these if statements you're going to want to establish that:

If current is in red, that the neighbor is not in red
if the current is in green that the neighbor is not in green

Then if the neighbor is not in green or red add the neighbor to the opposite color of current and then append it to the queue.

If the neighbor is in the same color as current return false.


On an entirely different note, you can't do the or like you have it in if neighbor not in red or green:. it would have to be something like if neighbor not in red and neighbor not in green

que.append(neighbor)
if current not in red:
red.add(neighbor)
que.pop()
elif current not in green:
green.add(neighbor)
que.pop()
else:
return False
return True





3 changes: 3 additions & 0 deletions tests/test_possible_bipartition.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ def test_example_1():
]

# Act



answer = possible_bipartition(dislikes)

# Assert
Expand Down