DawidS28

searchCycles.m

Mar 20th, 2016
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.27 KB | None | 0 0
  1. function cycleList = searchCycles(edgeMap)
  2.     tic
  3.     global graph cycles numCycles;
  4.     graph = edgeMap;
  5.     numCycles = 0;
  6.     cycles = {};
  7.     for i = 1:size(graph,1)
  8.         for j = 1:2
  9.             findNewCycles(graph(i,j))
  10.         end
  11.     end
  12.     % print out all found cycles
  13.     for i = 1:size(cycles,2)
  14.         cycles{i};
  15.     end
  16.    
  17.     % return the result
  18.     cycleList = cycles;
  19.     toc
  20. end
  21.  
  22. function findNewCycles(path)
  23.  
  24.     global graph cycles numCycles;
  25.     startNode = path(1);
  26.     nextNode = nan;
  27.     sub = [];
  28.  
  29.     % visit each edge and each node of each edge
  30.     for i = 1:size(graph,1)
  31.         node1 = graph(i,1);
  32.         node2 = graph(i,2);
  33.         if (node1 == startNode) || (node2==startNode) %% this if is required
  34.             if node1 == startNode
  35.                 nextNode = node2;
  36.             elseif node2 == startNode
  37.                 nextNode = node1;
  38.             end
  39.             if ~(visited(nextNode, path))
  40.                 % neighbor node not on path yet
  41.                 sub = nextNode;
  42.                 sub = [sub path];
  43.                 % explore extended path
  44.                 findNewCycles(sub);
  45.             elseif size(path,2) > 2 && nextNode == path(end)
  46.                 % cycle found
  47.                 p = rotate_to_smallest(path);
  48.                 inv = invert(p);
  49.                 if isNew(p) && isNew(inv)
  50.                     numCycles = numCycles + 1;
  51.                     cycles{numCycles} = p;
  52.                 end
  53.             end
  54.         end
  55.     end
  56. end
  57.  
  58. function inv = invert(path)
  59.     inv = rotate_to_smallest(path(end:-1:1));
  60. end
  61.  
  62. % rotate cycle path such that it begins with the smallest node
  63. function new_path = rotate_to_smallest(path)
  64.     [~,n] = min(path);
  65.     new_path = [path(n:end), path(1:n-1)];
  66. end
  67.  
  68. function result = isNew(path)
  69.     global cycles
  70.     result = 1;
  71.     for i = 1:size(cycles,2)
  72.         if size(path,2) == size(cycles{i},2) && all(path == cycles{i})
  73.             result = 0;
  74.             break;
  75.         end
  76.     end
  77. end
  78.  
  79. function result = visited(node,path)
  80.     result = 0;
  81.     if isnan(node) && any(isnan(path))
  82.         result = 1;
  83.         return
  84.     end
  85.     for i = 1:size(path,2)
  86.         if node == path(i)
  87.             result = 1;
  88.             break
  89.         end
  90.     end
  91. end
Advertisement
Add Comment
Please, Sign In to add comment