Skip to content

Instantly share code, notes, and snippets.

@Bablzz
Last active October 13, 2020 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bablzz/e46e72afc9738ac26234a78373357b94 to your computer and use it in GitHub Desktop.
Save Bablzz/e46e72afc9738ac26234a78373357b94 to your computer and use it in GitHub Desktop.
breadth-first search, BFS
# 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