-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueens.lua
More file actions
51 lines (43 loc) · 1003 Bytes
/
queens.lua
File metadata and controls
51 lines (43 loc) · 1003 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
N = 8
perm = {}
vis = {}
cnt = 0
function print_solution()
for r = 1, N do
for c = 1, N do
io.write(perm[r] == c and 'X' or '-', c == N and '\n' or ' ')
end
end
io.write('\n')
end
function dfs(k)
if k == N + 1 then
-- check if current permutation is a valid solution
main, sub = {}, {}
check = true
for i = 1, N do
mainIdx = 5 - perm[i] + i
subIdx = perm[i] + i
if main[mainIdx] or sub[subIdx] then
check = false
break
end
main[mainIdx] = true
sub[subIdx] = true
end
if check then
print_solution()
cnt = cnt + 1
end
end
for i = 1, N do
if not vis[i] then
vis[i] = true
perm[k] = i
dfs(k + 1)
vis[i] = false
end
end
end
dfs(1)
print(string.format("--> %d different solutions in total", cnt))