SHARE
TWEET

DFS

Infernale Oct 19th, 2019 182 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top