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

CS Fun B | Elaine Smith #72

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
32 changes: 31 additions & 1 deletion graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,35 @@ def possible_bipartition(dislikes):
Time Complexity: ?
Space Complexity: ?
"""
pass

if not dislikes:
return True

# Each dog will be sorted in either Group 1 or Group 2
dog_groups = {dog:0 for dog in dislikes} # Dogs w/ value 0 are still unsorted

# Choose a starting dog & place in Group 1
first_dog = list(dislikes.keys())[0]
dog_groups[first_dog] = 1

# Initialize the queue; this is how we will keep track of neighbors
# Keep track of which dogs haven't been sorted yet so they can be added to queue if queue is empty
dogs_to_sort = [dog for dog in dislikes]
queue = [first_dog]

for dog in dog_groups:
while queue:
current_dog = queue.pop(0)
dogs_to_sort.remove(current_dog)

for dog in dislikes[current_dog]:
if dog_groups[dog] == 0:
dog_groups[dog] = 2 if dog_groups[current_dog] == 1 else 1
if dog in dogs_to_sort:
queue.append(dog)
elif dog_groups[dog] == dog_groups[current_dog]:
return False
if dogs_to_sort:
queue.append(dogs_to_sort[0])
else:
return True