# Grafo como lista de adyacencia
graph = Dict(
"A" => ["B", "C"],
"B" => ["D", "E"],
"C" => ["F"],
"D" => [],
"E" => ["F"],
"F" => []
)
# BFS
function bfs(graph, start)
visited = Set()
queue = [start]
result = []
while !isempty(queue)
node = popfirst!(queue)
if !(node in visited)
push!(result, node)
push!(visited, node)
append!(queue, graph[node])
end
end
return result
end
# DFS
function dfs(graph, start)
visited = Set()
stack = [start]
result = []
while !isempty(stack)
node = pop!(stack)
if !(node in visited)
push!(result, node)
push!(visited, node)
append!(stack, reverse(graph[node]))
end
end
return result
end
# EjecuciĆ³n con temporizador
@
time bfs_result
= bfs
(graph
, "A")@
time dfs_result
= dfs
(graph
, "A")
# Resultados
println("BFS: ", bfs_result)
println("DFS: ", dfs_result)
IyBHcmFmbyBjb21vIGxpc3RhIGRlIGFkeWFjZW5jaWEKZ3JhcGggPSBEaWN0KAogICAgIkEiID0+IFsiQiIsICJDIl0sCiAgICAiQiIgPT4gWyJEIiwgIkUiXSwKICAgICJDIiA9PiBbIkYiXSwKICAgICJEIiA9PiBbXSwKICAgICJFIiA9PiBbIkYiXSwKICAgICJGIiA9PiBbXQopCgojIEJGUwpmdW5jdGlvbiBiZnMoZ3JhcGgsIHN0YXJ0KQogICAgdmlzaXRlZCA9IFNldCgpCiAgICBxdWV1ZSA9IFtzdGFydF0KICAgIHJlc3VsdCA9IFtdCgogICAgd2hpbGUgIWlzZW1wdHkocXVldWUpCiAgICAgICAgbm9kZSA9IHBvcGZpcnN0IShxdWV1ZSkKICAgICAgICBpZiAhKG5vZGUgaW4gdmlzaXRlZCkKICAgICAgICAgICAgcHVzaCEocmVzdWx0LCBub2RlKQogICAgICAgICAgICBwdXNoISh2aXNpdGVkLCBub2RlKQogICAgICAgICAgICBhcHBlbmQhKHF1ZXVlLCBncmFwaFtub2RlXSkKICAgICAgICBlbmQKICAgIGVuZAogICAgcmV0dXJuIHJlc3VsdAplbmQKCiMgREZTCmZ1bmN0aW9uIGRmcyhncmFwaCwgc3RhcnQpCiAgICB2aXNpdGVkID0gU2V0KCkKICAgIHN0YWNrID0gW3N0YXJ0XQogICAgcmVzdWx0ID0gW10KCiAgICB3aGlsZSAhaXNlbXB0eShzdGFjaykKICAgICAgICBub2RlID0gcG9wIShzdGFjaykKICAgICAgICBpZiAhKG5vZGUgaW4gdmlzaXRlZCkKICAgICAgICAgICAgcHVzaCEocmVzdWx0LCBub2RlKQogICAgICAgICAgICBwdXNoISh2aXNpdGVkLCBub2RlKQogICAgICAgICAgICBhcHBlbmQhKHN0YWNrLCByZXZlcnNlKGdyYXBoW25vZGVdKSkKICAgICAgICBlbmQKICAgIGVuZAogICAgcmV0dXJuIHJlc3VsdAplbmQKCiMgRWplY3VjacOzbiBjb24gdGVtcG9yaXphZG9yCkB0aW1lIGJmc19yZXN1bHQgPSBiZnMoZ3JhcGgsICJBIikKQHRpbWUgZGZzX3Jlc3VsdCA9IGRmcyhncmFwaCwgIkEiKQoKIyBSZXN1bHRhZG9zCnByaW50bG4oIkJGUzogIiwgYmZzX3Jlc3VsdCkKcHJpbnRsbigiREZTOiAiLCBkZnNfcmVzdWx0KQo=
0.110504 seconds (61.93 k allocations: 3.176 MiB, 99.92% compilation time)
0.029119 seconds (29.98 k allocations: 1.562 MiB, 99.75% compilation time)
BFS: Any["A", "B", "C", "D", "E", "F"]
DFS: Any["A", "B", "D", "E", "F", "C"]