Advertisement
Rochet2

Verkon kaksijakoisuus

Mar 22nd, 2015
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.41 KB | None | 0 0
  1. -- http://repl.it/erT/1
  2.  
  3. local WHITE = nil
  4. local RED = 0
  5. local BLACK = 1
  6.  
  7. local function visit(M, color, lastcolor, i)
  8.     local pickedcolor = (lastcolor+1) % 2
  9.     if (color[i] == WHITE) then
  10.         color[i] = pickedcolor
  11.         for j = 1, #M do
  12.             if (i ~= j and (M[i][j] == 1 or M[j][i] == 1)) then
  13.                 if (not visit(M, color, pickedcolor, j)) then
  14.                     return false
  15.                 end
  16.             end
  17.         end
  18.     elseif (color[i] ~= pickedcolor) then
  19.         return false
  20.     end
  21.     return true
  22. end
  23.  
  24. local function cantwocolor(M)
  25.     local color = {}
  26.     for i = 1, #M do
  27.         if (color[i] == WHITE) then
  28.             if (not visit(M, color, 0, i)) then
  29.                 return false
  30.             end
  31.         end
  32.     end
  33.     return true
  34. end
  35.  
  36. local M1 = {
  37.     {0,1,0,0},
  38.     {0,0,1,0},
  39.     {0,0,0,1},
  40.     {1,0,0,0},
  41. }
  42. local M2 = {
  43.     {0,1,0},
  44.     {0,0,1},
  45.     {1,0,0},
  46. }
  47. local M3 = {
  48.     {0,1,1,0,0,0},
  49.     {1,0,0,1,0,0},
  50.     {0,0,0,0,0,1},
  51.     {0,0,0,0,0,0},
  52.     {1,0,1,0,0,0},
  53.     {0,0,0,0,0,0},
  54. }
  55. local M4 = {
  56.     {0,1,1,0,0,0,0},
  57.     {1,0,0,1,0,0,0},
  58.     {0,0,0,0,0,1,0},
  59.     {0,0,0,0,0,0,0},
  60.     {1,0,0,0,0,0,1},
  61.     {0,0,0,0,0,0,0},
  62.     {0,0,1,0,0,0,0},
  63. }
  64.  
  65. print(cantwocolor(M1), "expected", true)
  66. print(cantwocolor(M2), "expected", false)
  67. print(cantwocolor(M3), "expected", false)
  68. print(cantwocolor(M4), "expected", true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement