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

Branches - Xinran #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
38 changes: 37 additions & 1 deletion lib/possible_bipartition.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,40 @@

def possible_bipartition(dislikes)
raise NotImplementedError, "possible_bipartition isn't implemented yet"
visited = {}
q1 = []
hash1 = {}
q2 = []
hash2 = {}

i = 0
while i < dislikes.length
if dislikes[i] != [] && !visited[i]
q1 << i
hash1[i] = true
while q1.length > 0 || q2.length > 0
return false if !bfs(q1, q2, hash1, hash2, visited, dislikes)
return false if !bfs(q2, q1, hash2, hash1, visited, dislikes)
end
end
i += 1
end
return true
end

def bfs(q1, q2, hash1, hash2, visited, dislikes)

Choose a reason for hiding this comment

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

I like how you did BFS with 2 queues!

while q1.length > 0
dog1 = q1.shift
visited[dog1] = true
dislikes[dog1].each do |dog|
if hash1[dog]
return false
else
if !visited[dog]
hash2[dog] = true
q2 << dog
end
end
end
end
return true
end
20 changes: 20 additions & 0 deletions test/possible_bipartition_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,26 @@
expect(answer).must_equal false
end

it "will return false for a graph which cannot be bipartitioned" do

Choose a reason for hiding this comment

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

👍

# Arrange
dislikes = [ [3, 6],
[2, 5],
[1, 3],
[0, 2, 4],
[3, 5],
[1, 4],
[0],
[8],
[7]
]

# Act
answer = possible_bipartition(dislikes)

# Assert
expect(answer).must_equal false
end

it "will work for an empty graph" do
expect(possible_bipartition([])).must_equal true
end
Expand Down