From 1e60a0ccac974d5f4a5933d6770a24207647796d Mon Sep 17 00:00:00 2001 From: Nikki Torab Date: Mon, 16 Jan 2023 20:00:41 -0800 Subject: [PATCH] solved --- graphs/possible_bipartition.py | 39 +++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/graphs/possible_bipartition.py b/graphs/possible_bipartition.py index ca55677..ad2afe6 100644 --- a/graphs/possible_bipartition.py +++ b/graphs/possible_bipartition.py @@ -1,12 +1,35 @@ -# 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: ? - """ - pass + + if not dislikes: + return True + + dogs = {dog: -1 for dog in dislikes.keys()} + + def breadth_first(start): + dogs[start] + q = deque() + q.append(start) + + while q: + curr = q.popleft() + for node in dislikes[curr]: + + if dogs[node] == -1: + dogs[node] = 1 - dogs[curr] + q.append(node) + + elif dogs[node] == dogs[curr]: + return False + + return True + + for dog in dislikes.keys(): + + if dogs[dog] == -1: + if not breadth_first(dog): + return False + + return True