fork download
  1. /*
  2. Implementación iterativa DFS
  3. https://g...content-available-to-author-only...b.com/orendon/01cf8cd0794f7869ce16d152c0131c79
  4. A
  5. / \
  6. B E
  7. / \ / \
  8. C D F G
  9. */
  10.  
  11. let stack = []
  12. let visited = {} // para marcar los nodos que ya visitamos
  13. const adjacency_list = { // guardamos los "vecinos/hijos" de cada nodo
  14. 'A': ['B', 'E'],
  15. 'B': ['C', 'D'],
  16. 'C': [],
  17. 'D': [],
  18. 'E': ['F', 'G'],
  19. 'F': [],
  20. 'G': [],
  21. }
  22.  
  23. function dfs(origin){
  24. stack.push(origin);
  25.  
  26. while(stack.length > 0){
  27. const node = stack.pop();
  28. console.log(node);
  29.  
  30. for(const child of adjacency_list[node]) {
  31. if (!visited[child]){
  32. stack.push(child);
  33. }
  34. };
  35. }
  36. }
  37.  
  38.  
  39. dfs('A');
  40.  
Success #stdin #stdout 0.06s 29896KB
stdin
Standard input is empty
stdout
A
E
G
F
B
D
C