orig.lua 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. N = 8 -- board size
  2. -- check whether position (n,c) is free from attacks
  3. function isplaceok(a, n, c)
  4. for i = 1, n - 1 do -- for each queen already placed
  5. if (a[i] == c) or -- same column?
  6. (a[i] - i == c - n) or -- same diagonal?
  7. (a[i] + i == c + n) then -- same diagonal?
  8. return false -- place can be attacked
  9. end
  10. end
  11. return true -- no attacks; place is OK
  12. end
  13. -- print a board
  14. function printsolution(a)
  15. for i = 1, N do -- for each row
  16. for j = 1, N do -- and for each column
  17. -- write "X" or "-" plus a space
  18. io.write(a[i] == j and "X" or "-", " ")
  19. end
  20. io.write("\n")
  21. end
  22. io.write("\n")
  23. end
  24. -- add to board 'a' all queens from 'n' to 'N'
  25. function addqueen(a, n)
  26. if n > N then -- all queens have been placed?
  27. printsolution(a)
  28. else -- try to place n-th queen
  29. for c = 1, N do
  30. if isplaceok(a, n, c) then
  31. a[n] = c -- place n-th queen at column 'c'
  32. addqueen(a, n + 1)
  33. end
  34. end
  35. end
  36. end
  37. -- run the program
  38. addqueen({}, 1)