From 7ea42a94cf0da1b7e5761f076bf2b41d343d3e6f Mon Sep 17 00:00:00 2001 From: Elaine Smith Date: Sat, 31 Dec 2022 12:20:32 -0800 Subject: [PATCH] Project complete; All tests pass --- graphs/possible_bipartition.py | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/graphs/possible_bipartition.py b/graphs/possible_bipartition.py index ca55677..f9dba5e 100644 --- a/graphs/possible_bipartition.py +++ b/graphs/possible_bipartition.py @@ -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