local file = io.open('output.txt', 'w')
io.output(file)
local N = 8local a = {}
local times = 0localfunctionis_place_ok(n, c)-- n >=1 and n <= 8for i = 1, n - 1doif (a[i] == c) or (math.abs(a[i] - c) == math.abs(n - i)) thenreturnfalseendendreturntrueendlocalfunctionshow()
times = times + 1io.write('Times ', times, '\n')
for i = 1, N dofor j = 1, N doif a[i] == j thenio.write('X ')
elseio.write('- ')
endendio.write('\n')
endendlocalfunctionadd_queen(n)if n > N then
show()
elsewhile (a[n] <= N)
doif is_place_ok(n, a[n]) thenbreakend
a[n] = a[n] + 1endif a[n] <= N then
a[n + 1] = 1
add_queen(n + 1)
else-- 回溯
n = n - 1
a[n] = a[n] + 1
add_queen(n)
endendendlocalfunctioninit()for i = 1, N do
a[i] = 1-- lua 中index从1开始endend
init();
add_queen(1)
io.close()
全解递归算法
local file = io.open('output.txt', 'w')
io.output(file)
local N = 8local a = {}
local times = 0localfunctionis_place_ok(n, c)-- n >=1 and n <= 8for i = 1, n - 1doif (a[i] == c) or (math.abs(a[i] - c) == math.abs(n - i)) thenreturnfalseendendreturntrueendlocalfunctionshow()
times = times + 1io.write('Times ', times, '\n')
for i = 1, N dofor j = 1, N doif a[i] == j thenio.write('X ')
elseio.write('- ')
endendio.write('\n')
endendlocalfunctionadd_queen(n)if n > N then
show()
elsefor c = 1, N doif is_place_ok(n, c) then
a[n] = c
add_queen(n + 1)
endendendendlocalfunctioninit()for i = 1, N do
a[i] = 1-- lua 中index从1开始endend
init();
add_queen(1)
io.close()
单解递归算法local file = io.open('output.txt', 'w')io.output(file)local N = 8local a = {} local times = 0local function is_place_ok(n, c) -- n >=1 and n <= 8 for i = 1, n - 1 do if (a[i] == c)