Advertisement
Infernale

DFS

Oct 19th, 2019
3,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scilab 0.82 KB | None | 0 0
  1. global nodes;
  2.  
  3. function DFS(graph, visited, start)
  4.     visited(1, start) = 1;
  5.     mprintf("%d ", start);
  6.     for i=1:nodes
  7.         if graph(start, i) == 1 & visited(1, i) == 0 then
  8.             DFS(graph, visited, i);
  9.         end
  10.     end
  11. endfunction
  12.  
  13. function [from, to]=split(data)
  14.     splitted = evstr(strsplit(data, " "));
  15.     from = splitted(1, 1);
  16.     to = splitted(2, 1);
  17. endfunction
  18.  
  19. nodes = input("How many nodes ? ");
  20. graph = zeros(nodes, nodes);
  21. edges = input("How many edges ? ");
  22. disp("Enter " + string(edges) + " edges (from-to) separated by a white space:");
  23. for i=1:edges
  24.     in = input("", "string");
  25.     [from, to] = split(in);
  26.     graph(from, to) = 1;
  27.     graph(to, from) = 1;  
  28. end
  29.    
  30. startNode = input("Enter initial node : ");
  31.  
  32. visited = zeros(1, nodes);
  33. DFS(graph, visited, startNode);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement