Advertisement
Rochet2

Verkon alkusolmu Lua pseudokoodi TIRA

Mar 22nd, 2015
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.09 KB | None | 0 0
  1. -- http://repl.it/eqz/7
  2.  
  3. local WHITE = nil   -- not visited
  4. local GRAY  = 1     -- visited
  5. local RED   = 2     -- visited and possible startvertex (must have one)
  6.  
  7. -- visit vertex and mark visited
  8. local function visit(L, color, startvertex, i)
  9.     -- if we can access a startvertex it can not be the startvertex, so we remove it.
  10.     if (color[i] == RED) then
  11.         startvertex[i] = nil
  12.         startvertex.count = startvertex.count-1
  13.     end
  14.    
  15.     -- if we have not yet visited this vertex, visit it
  16.     if (color[i] == WHITE) then
  17.         -- mark visited
  18.         color[i] = GRAY
  19.        
  20.         -- visit all it's neighbours
  21.         for j = 1, #L[i] do
  22.             visit(L, color, startvertex, L[i][j])
  23.         end
  24.     end
  25. end
  26.  
  27. -- takes in an adjacency list, outputs true or false
  28. local function hasstartvertex(L)
  29.     -- list of start vertexes and count of them
  30.     local startvertex = {count = 0}
  31.     -- vertex colors, see top of code
  32.     local color = {}
  33.    
  34.     -- go through all vertexes, visit them and their adjacents and mark the
  35.     -- starting node as possible starvertex. We only go through not visited vertexes
  36.     for i = 1, #L do
  37.         if (color[i] == WHITE) then
  38.             -- visit the vertex and it's adjacents
  39.             visit(L, color, startvertex, i)
  40.            
  41.             -- set the vertex as possible startvertex
  42.             startvertex[i] = true
  43.             startvertex.count = startvertex.count+1
  44.             color[i] = RED
  45.         end
  46.     end
  47.  
  48.     -- in the end there must be only one start vertex since start vertexes can't
  49.     -- be reached from each other.
  50.     return startvertex.count == 1
  51. end
  52.  
  53. -- Test lists:
  54.  
  55. -- complex net, false
  56. local L1 = {
  57.     {2, 3},
  58.     {1, 4},
  59.     {6},
  60.     {},
  61.     {1, 3},
  62.     {},
  63.     {4},
  64. }
  65. -- complex net, true
  66. local L2 = {
  67.     {2, 3},
  68.     {1, 4},
  69.     {6},
  70.     {},
  71.     {1, 3},
  72.     {},
  73. }
  74.  
  75. -- loop, true
  76. local L3 = {
  77.     {2},
  78.     {3},
  79.     {4,2},
  80.     {1},
  81. }
  82.  
  83. print(hasstartvertex(L1), "expected", false)
  84. print(hasstartvertex(L2), "expected", true)
  85. print(hasstartvertex(L3), "expected", true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement