Advertisement
Infernale

BFS

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