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

Adkisson - C17 - cs_fun_b #83

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
50 changes: 43 additions & 7 deletions graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,48 @@
# Can be used for BFS
from collections import deque
from collections import defaultdict, 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: ?
"""
Will return True or False if the given graph
can be bipartitioned without neighboring nodes put
into the same partition.
Time Complexity: O(N)^2
Space Complexity: O(N)

Example -
input:
dislikes = {
"Fido": [],
"Nala": ["Cooper", "Spot"],
"Cooper": ["Nala", "Bruno"],
"Spot": ["Nala"],
"Bruno": ["Cooper"]
}
output:
True
"""
pass
#
if len(dislikes) == 0:
return True

play_area = {}
stack = []

for dog in dislikes:
# assign unassigned dog to play area + add to stack
if dog not in play_area:
stack.append(dog)
play_area[dog] = 0
# look at stack and check neighbors
while stack:
current = stack.pop()
# assign neighbors to group
for neighbor in dislikes[current]:
if neighbor not in play_area:
stack.append(neighbor)
play_area[neighbor] = 1 - play_area[current]
elif play_area[neighbor] == play_area[current]:
return False

return True