Advertisement
Tooster

hamilton brute

Jan 9th, 2019
392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.83 KB | None | 0 0
  1. S = {}
  2. vis = {}
  3. n = 20
  4. function clone(tab)
  5.     local r = {}
  6.     for k,v in pairs(tab) do r[k] = v end
  7.     return r
  8. end
  9.  
  10. function gen(perm)
  11.     local perms = {}
  12.     for i=1,#perm-1 do
  13.         if perm[i] ~= perm[i+1] then
  14.             local p = clone(perm)
  15.             p[i], p[i+1] = p[i+1], p[i]
  16.             perms[#perms+1] = p
  17.         end
  18.     end
  19.     return perms
  20. end
  21.  
  22. u = {'a', 'a', 'a', 'b', 'b', 'b'}
  23. function hamilton(v, step)
  24.   if(step==n) then
  25.     S[#S+1] = table.concat(v)
  26.     return true
  27.   end
  28.   vis[table.concat(v)] = true
  29.   for _, w in ipairs(gen(v)) do
  30.     if not vis[table.concat(w)] and hamilton(w, step+1) then
  31.       S[#S+1] = table.concat(v)
  32.       return true
  33.     end
  34.   end
  35.   vis[table.concat(v)] = false
  36.   return false
  37. end
  38.  
  39. hamilton(u, 1)
  40.  
  41. for i=#S,1,-1 do print("\""..S[i].."\",") end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement