Last active
October 13, 2020 14:14
-
-
Save Bablzz/e46e72afc9738ac26234a78373357b94 to your computer and use it in GitHub Desktop.
breadth-first search, BFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# O(|V|+|E|) | |
graph = Hash.new | |
graph["you"] = ["alice", "bob", "claire"] | |
graph["bob"] = ["anuj", "peggy"] | |
graph["alice"] = ["peggy"] | |
graph["claire"] = ["thom", "jonny"] | |
graph["anuj"] = [] | |
graph["peggy"] = [] | |
graph["thom"] = [] | |
graph["jonny"] = [] | |
queue = [graph] | |
def is_person_seller name | |
name[-1] == "m" unless name.nil? | |
end | |
def search graph, name | |
searched = [] | |
queue = graph[name] | |
puts "QUEUE FROM EACH #{queue}" | |
until queue.empty? | |
q = queue.shift | |
unless searched.include? q | |
if is_person_seller(q) | |
puts "#{q} is a mango seller in #{name}" | |
else | |
puts "NAME FROM EACH #{q}" | |
queue += graph[q] unless graph[q].empty? | |
searched << q | |
end | |
end | |
end | |
end | |
search(graph, "you") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment