fork download
  1. # Grafo como lista de adyacencia
  2. graph = Dict(
  3. "A" => ["B", "C"],
  4. "B" => ["D", "E"],
  5. "C" => ["F"],
  6. "D" => [],
  7. "E" => ["F"],
  8. "F" => []
  9. )
  10.  
  11. # BFS
  12. function bfs(graph, start)
  13. visited = Set()
  14. queue = [start]
  15. result = []
  16.  
  17. while !isempty(queue)
  18. node = popfirst!(queue)
  19. if !(node in visited)
  20. push!(result, node)
  21. push!(visited, node)
  22. append!(queue, graph[node])
  23. end
  24. end
  25. return result
  26. end
  27.  
  28. # DFS
  29. function dfs(graph, start)
  30. visited = Set()
  31. stack = [start]
  32. result = []
  33.  
  34. while !isempty(stack)
  35. node = pop!(stack)
  36. if !(node in visited)
  37. push!(result, node)
  38. push!(visited, node)
  39. append!(stack, reverse(graph[node]))
  40. end
  41. end
  42. return result
  43. end
  44.  
  45. # EjecuciĆ³n con temporizador
  46. @time bfs_result = bfs(graph, "A")
  47. @time dfs_result = dfs(graph, "A")
  48.  
  49. # Resultados
  50. println("BFS: ", bfs_result)
  51. println("DFS: ", dfs_result)
  52.  
Success #stdin #stdout 1.34s 270352KB
stdin
Standard input is empty
stdout
  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"]