Skip to content

Instantly share code, notes, and snippets.

@zhenyanghua
Last active August 10, 2021 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhenyanghua/29ac1784ca9515c566a205cdc8032c10 to your computer and use it in GitHub Desktop.
Save zhenyanghua/29ac1784ca9515c566a205cdc8032c10 to your computer and use it in GitHub Desktop.
Eight queens puzzle
--[[
List all solutions that eight queens on the chess board can't attach each other
example output:
x - - - - - - -
- - - - x - - -
- - - - - - - x
- - - - - x - -
- - x - - - - -
- - - - - - x -
- x - - - - - -
- - - x - - - -
]]--
-- size of the chess board
N = 8
function isPlaceOk(a, row, col)
for i = 1, row - 1 do
if a[i] == col or -- check any queen in the same column
row - i == col - a[i] or --[[
check any queen in the diagonal (top-left -> bottom-right)
we use the slope value: k1 = (y2-y1) / (x2 - x1) where k1 = 1 to test the diagonal
the other direction is k2 = -k1
]]--
row - i == -1 * (col - a[i]) then -- check any queen in the diagonal (top-right -> bottom-left)
return false
end
end
return true
end
function draw(a)
for row = 1, N do
for col = 1, N do
io.write(a[row] == col and 'x' or '-', ' ')
end
io.write('\n')
end
io.write('\n')
end
--[[
for each row, test each column and its following row (apply the same to the following row)
until it completes all rows.
]]--
function addQueen(a, row)
if (row > N) then
draw(a) -- draw the solution when it is complete.
else
for col = 1, N do
if isPlaceOk(a, row, col) then
a[row] = col
addQueen(a, row + 1)
end
end
end
end
addQueen({}, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment