Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. N = 8 -- board size
  2.  
  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.  
  14. -- print a board
  15. function printsolution(a)
  16. for i = 1, N do --for each row
  17. for j = 1, N do -- and for each column
  18. -- writes "X" or "-" plus space
  19. io.write(a[i] == j and "X" or "-"," ")
  20. end
  21. io.write("\n")
  22. end
  23. io.write("\n")
  24. end
  25.  
  26. -- add to board 'a' all queens from 'n' to 'N'
  27. function addqueen(a, n)
  28. if n > N then -- all queens have been placed?
  29. printsolution(a)
  30. else -- try to place the n-th queen
  31. for c = 1, N do
  32. if isplaceok(a, n, c) then
  33. a[n] = c -- place the n-th queen at column 'c'
  34. addqueen(a, n+1)
  35. end
  36. end
  37. end
  38. end
  39.  
  40. -- run the program
  41. addqueen({}, 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement