N-queens problem: Difference between revisions

m
→‎Python: Backtracking on permutations: Restored the original look
(→‎{{header|Tailspin}}: Update to latest version. Use types more effectively)
m (→‎Python: Backtracking on permutations: Restored the original look)
 
(46 intermediate revisions by 15 users not shown)
Line 1:
{{taskTask}}
[[File:chess_queen.jpg|400px||right]]
 
Line 26:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">-V BoardSize = 8
 
F underAttack(col, queens)
Line 57:
print(‘ ’, end' ‘’)
print(Char(code' ‘a’.code + row)‘’col, end' ‘’)
print(end' I L.index % 4 == 3 {"\n"} E ‘ ’)</langsyntaxhighlight>
 
{{out}}
Line 92:
Translated from the Fortran 77 solution.<br>
For maximum compatibility, this program uses only the basic instruction set (S/360).
<langsyntaxhighlight lang="360asm">* N-QUEENS PROBLEM 04/09/2015
MACRO
&LAB XDECO &REG,&TARGET
Line 233:
U DC (4*LL-2)H'0' stack
REGS make sure to include copybook jcl
END NQUEENS</langsyntaxhighlight>
{{out}}
<pre>
Line 252:
</pre>
 
=={{header|6502 Assembly}}==
{{trans|Java}}
A few optimization techniques are used in this implementation. One goal was to get 8-queens to run in under 2 seconds on a 1 MHz computer.
 
Zero page values are stored where frequent use of the immediate addressing mode can be used as a speed up. This can be seen where a byte is referenced as variablename+1. INC and DEC instructions are used instead of ADC and SBC instructions for the comparison offsets.
 
The solution count is a 64-bit little endian value stored in memory starting at $0020, or $0D20 if the [[#Zero Page stub|Zero Page stub]] routine is used.
 
<syntaxhighlight lang="6502asm">n equ 8 ; queens
maximum equ 32 ; only limited by time
place equ $00
count equ maximum+place ; 64 bits (8 bytes)
length equ maximum+8
org $80
start
LDY #n ; n queens on an n x n board
STY greater+1
DEY
STY safe+1
LDX #length
LDA #$00
clear
STA place,X
DEX
BPL clear
next
INX
LDA #$FF
STA place,X
loop
INC place,X
LDA place,X
greater
CMP #n
BCS max
STX index+1
index
LDY #$00 ; index+1
BEQ safe
DEY
STA compare+1
STA add+1 ; compare
STA sub+1 ; compare
issafe
LDA place,Y
compare
CMP #$00 ; compare+1
BEQ loop ; unsafe
INC add+1
add
CMP #$00 ; add+1
BEQ loop ; unsafe
DEC sub+1
sub
CMP #$00 ; sub+1
BEQ loop ; unsafe
DEY
BPL issafe
safe
CPX #n-1
BNE next
INC count ; 64 bits (8 bytes)
BNE loop
INC count+1
BNE loop
INC count+2
BNE loop
INC count+3
BNE loop
INC count+4
BNE loop
INC count+5
BNE loop
INC count+6
BNE loop
INC count+7
BNE loop
BRK
max
DEX
BPL loop
; RTS</syntaxhighlight>
The code was assembled using Merlin32. The code length is 104 bytes not including the final 6 cycle RTS instruction.
<pre> n solutions cycles
1 1 443
2 0 710
3 0 1440
4 2 4359
5 10 17134
6 4 75848
7 40 337161
8 92 1616054
9 352 8044019
10 724 41556729
11 2680 230829955
12 14200 1378660940
13 73712 8684130248
14 365596 58185218171
15 2279184 412358679630
</pre>
==== Zero Page stub ====
The 6502 N-queens problem code resides within the zero page starting at $80 which can make running the program a bit tricky on some platforms. A stub is provided to facilitate running the zero page code. The stub routine turns off interrupts and swaps the zero page memory with an area residing at $D00 to $DFF, runs the zero page code, and swaps memory again. The cycle counts listed above do not include the time to run this stub. With the final RTS instruction included, the 105 byte N-queens zero page code must be in memory starting at $D80.
<syntaxhighlight lang="6502asm"> org $C00
PHP
SEI
JSR swap
JSR $0080
JSR swap
PLP
jmp end
swap
LDX #$00
loop
LDY $D00,X
LDA $00,X
STY $00,X
STA $D00,X
INX
BNE loop
RTS
end
; RTS</syntaxhighlight>
=={{header|ABAP}}==
<syntaxhighlight lang="abap">
<lang ABAP>
TYPES: BEGIN OF gty_matrix,
1 TYPE c,
Line 539 ⟶ 661:
SKIP 1.
ENDFORM. " SHOW_MATRIX
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Queens is
Line 591 ⟶ 713:
end loop;
Put_Line (" A B C D E F G H");
end Queens;</langsyntaxhighlight>
{{out}}
<pre>
Line 610 ⟶ 732:
This one only counts solutions, though it's easy to do something else with each one (instead of the <code>M := M + 1;</code> line).
 
<langsyntaxhighlight lang="ada">with Ada.Text_IO;
use Ada.Text_IO;
 
Line 658 ⟶ 780:
Put_Line (Long_Integer'Image (Queens (N)));
end loop;
end CountQueens;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 668 ⟶ 790:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8.8d.fc9.i386]}}
<langsyntaxhighlight Algol68lang="algol68">INT ofs = 1, # Algol68 normally uses array offset of 1 #
dim = 8; # dim X dim chess board #
[ofs:dim+ofs-1]INT b;
Line 718 ⟶ 840:
FI
OD
)</langsyntaxhighlight>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
More or less copied from the "DFS" lesson on tryapl.org .
<syntaxhighlight lang="apl">
<lang APL>
⍝Solution
accm←{⍺,((⍴⍵)=⍴⊃⍺)↑⊂⍵}
Line 735 ⟶ 857:
⍝Example
printqueens 6
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 769 ⟶ 891:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">-- Finds all possible solutions and the unique patterns.
 
property Grid_Size : 8
Line 932 ⟶ 1,054:
return newRows
end Reflect</langsyntaxhighlight>
 
=={{header|Applesoft BASIC}}==
{{trans|Java}}
<syntaxhighlight lang="basic"> 1 READ N,T,M,R(0): FOR Y = 0 TO M STEP 0: FOR L = 0 TO T STEP 0:R(Y) = R(Y) + T:X = R(Y):C = NOT Y: IF NOT C THEN FOR I = T TO Y:A = R(Y - I): IF NOT (A = X OR A = X - I OR A = X + I) THEN NEXT I:C = T
2 L = R(Y) > N OR C: NEXT L:D = - (R(Y) > N): IF NOT D AND Y < N THEN R(Y + T) = M:D = D + T
3 S = S + NOT D:Y = Y + D: NEXT Y: PRINT "THERE " MID$ ("AREIS",4 ^ (S = 1),3)" "S" SOLUTION" MID$ ("S",1,S < > 1)" FOR "N + T" X "N + T: DATA7,1,-1,-1</syntaxhighlight>
{{out}}
<pre>THERE ARE 92 SOLUTIONS FOR 8 X 8
</pre>
 
=={{header|Arc}}==
This program prints out all possible solutions:
<langsyntaxhighlight Lisplang="lisp">(def nqueens (n (o queens))
(if (< len.queens n)
(let row (if queens (+ 1 queens.0.0) 0)
Line 955 ⟶ 1,086:
(def diagonal-match (curr other)
(is (abs (- curr.0 other.0))
(abs (- curr.1 other.1))))</langsyntaxhighlight>
{{out}}
The output is one solution per line, each solution in the form `((row col) (row col) (row col) ...)`:
Line 964 ⟶ 1,095:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="arturo">result: new []
 
queens: function [n, i, a, b, c][
Line 995 ⟶ 1,126:
]
print ""
]</langsyntaxhighlight>
 
{{out}}
Line 1,029 ⟶ 1,160:
=={{header|AWK}}==
Inspired by Raymond Hettinger's Python solution, but builds the vector incrementally.
<langsyntaxhighlight lang="awk">
#!/usr/bin/gawk -f
# Solve the Eight Queens Puzzle
Line 1,103 ⟶ 1,234:
 
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,118 ⟶ 1,249:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 1,199 ⟶ 1,330:
 
(* end of [queens.dats] *)
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
=== Output to formatted Message box ===
{{trans|C}}
<syntaxhighlight lang="autohotkey">;
<lang AutoHotkey>;
; Post: http://www.autohotkey.com/forum/viewtopic.php?p=353059#353059
; Timestamp: 05/may/2010
Line 1,283 ⟶ 1,414:
Output .= "|`n" , yyy++
}
}</langsyntaxhighlight>
=== Includes a solution browser GUI ===
This implementation supports N = 4..12 queens, and will find ALL solutions
Line 1,289 ⟶ 1,420:
The screenshot shows the first solution of 10 possible solutions for N = 5 queens.
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">N := 5
Number: ; main entrance for different # of queens
SI := 1
Line 1,378 ⟶ 1,509:
 
GuiClose:
ExitApp</langsyntaxhighlight>
[[image:N-Queens_SolutionBrowserGUI.png]]
 
Line 1,387 ⟶ 1,518:
[[Image:queens9_bbc.gif|right]]
[[Image:queens10_bbc.gif|right]]
<langsyntaxhighlight lang="bbcbasic"> Size% = 8
Cell% = 32
VDU 23,22,Size%*Cell%;Size%*Cell%;Cell%,Cell%,16,128+8,5
Line 1,447 ⟶ 1,578:
ENDWHILE
UNTIL i% = 0
= m%</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight BCPLlang="bcpl">// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10.
 
GET "libhdr.h"
Line 1,480 ⟶ 1,611:
RESULTIS 0
}
</syntaxhighlight>
</lang>
The following is a re-implementation of the algorithm given above but
using the MC package that allows machine independent runtime generation
Line 1,486 ⟶ 1,617:
It runs about 25 times faster that the version given above.
 
<syntaxhighlight lang="bcpl">
<lang BCPL>
GET "libhdr.h"
GET "mc.h"
Line 1,621 ⟶ 1,752:
i, n, all)
}
</syntaxhighlight>
</lang>
 
=={{header|Befunge}}==
Line 1,627 ⟶ 1,758:
This algorithm works with any board size from 4 upwards.
 
<langsyntaxhighlight lang="befunge"><+--XX@_v#!:-1,+55,g\1$_:00g2%-0vv:,+55<&,,,,,,"Size: "
"| Q"$$$>:01p:2%!00g0>>^<<!:-1\<1>00p::2%-:40p2/50p2*1+
!77**48*+31p\:1\g,::2\g:,\3\g,,^g>0g++40g%40g\-\40g\`*-
2g05\**!!%6g04-g052!:`\g05::-1/2<^4*2%g05\+*+1*!!%6g04-</langsyntaxhighlight>
 
{{out}}
Line 1,655 ⟶ 1,786:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( printBoard
= board M L x y S R row line
. :?board
Line 1,715 ⟶ 1,846:
| out$(found !solutions solutions)
)
);</langsyntaxhighlight>
{{out}} (tail):
<pre>
Line 1,760 ⟶ 1,891:
 
=={{header|C}}==
C99, compiled with <code>gcc -std=c99 -Wall</code>. Take one commandline argument: size of board, or default to 8. Shows the board layout for each solution.<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,790 ⟶ 1,921:
int hist[n];
solve(n, 0, hist);
}</langsyntaxhighlight>
 
Similiar to above, but using bits to save board configurations and quite a bit faster:<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 1,829 ⟶ 1,960:
printf("\nSolutions: %d\n", count);
return 0;
}</langsyntaxhighlight>
Take that and unwrap the recursion, plus some heavy optimizations, and we have a very fast and very unreadable solution:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,921 ⟶ 2,052:
printf("\nSolutions: %d\n", count);
return 0;
}</langsyntaxhighlight>
 
A slightly cleaned up version of the code above where some optimizations were redundant. This version is also further optimized, and runs about 15% faster than the one above on modern compilers:
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#define MAXN 31
 
Line 1,994 ⟶ 2,125:
printf("Number of solution for %d is %d\n",n,nqueens(n));
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Line 2,007 ⟶ 2,138:
{{works with|C sharp|C#|7}}
<!-- By Martin Freedman, 13/02/2018 -->
<langsyntaxhighlight lang="csharp">using System.Collections.Generic;
using static System.Linq.Enumerable;
using static System.Console;
Line 2,049 ⟶ 2,180:
public static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }
}
}</langsyntaxhighlight>
Output
<pre>8-queens has 92 solutions
Line 2,057 ⟶ 2,188:
===Hettinger Algorithm===
Compare this to the Hettinger solution used in the first Python answer. The logic is similar but the diagonal calculation is different and more expensive computationally (Both suffer from being unable to eliminate permutation prefixes that are invalid e.g. 0 1 ...)
<langsyntaxhighlight lang="csharp">
using System.Collections.Generic;
using static System.Linq.Enumerable;
Line 2,095 ⟶ 2,226:
public static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }
}
}</langsyntaxhighlight>
=== Amb solution===
This uses the second version of the [https://rosettacode.org/wiki/Amb#C.23 Amb C# class] in the Amb challenge. Really that is not McCarthy's Amb (Ambiguous function) and here it is used just as a simple general interface by lambdas to a standalone backtrack algorithm. Due to the specification of the Amb challenge, this, ironically (given the notion of ambiguous functions), only produces one solution not 92. It is trivial to update Amb (might be better called a backtracker rather than Amb too) but here it is just used to show how easy it is to go from a generate and prune Linq solution to a backtrack solution. The Linq filters becoming "amb" requirements.
{{works with|C sharp|C#|7.1}}
<!-- By Martin Freedman, 9/02/2018 -->
<langsyntaxhighlight lang="csharp">using static System.Linq.Enumerable;
using static System.Console;
 
Line 2,128 ⟶ 2,259:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">// Much shorter than the version below;
// uses C++11 threads to parallelize the computation; also uses backtracking
// Outputs all solutions for any table size
Line 2,234 ⟶ 2,365:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}Output for N = 4:
<pre> a b c d
Line 2,248 ⟶ 2,379:
3 #
4 # </pre>
<langsyntaxhighlight lang="cpp">
// A straight-forward brute-force C++ version with formatted output,
// eschewing obfuscation and C-isms, producing ALL solutions, which
Line 2,506 ⟶ 2,637:
std::cout << queens( N ) << "\n";
}
</syntaxhighlight>
</lang>
{{out}} for N=4:
<pre>
Line 2,527 ⟶ 2,658:
=== Alternate version ===
Windows-only
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 2,628 ⟶ 2,759:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,657 ⟶ 2,788:
 
Version using Heuristics - explained here: [http://en.wikipedia.org/wiki/8_queens_puzzle#Solution_construction Solution_construction]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 2,746 ⟶ 2,877:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
This produces all solutions by essentially a backtracking algorithm. The heart is the ''extends?'' function, which takes a partial solution for the first ''k<size'' columns and sees if the solution can be extended by adding a queen at row ''n'' of column ''k+1''. The ''extend'' function takes a list of all partial solutions for ''k'' columns and produces a list of all partial solutions for ''k+1'' columns. The final list ''solutions'' is calculated by starting with the list of 0-column solutions (obviously this is the list ''[ [] ]'', and iterates ''extend'' for ''size'' times.
<langsyntaxhighlight lang="clojure">(def size 8)
 
(defn extends? [v n]
Line 2,772 ⟶ 2,903:
(println s))
 
(println (count solutions) "solutions")</langsyntaxhighlight>
===Short Version===
<langsyntaxhighlight lang="clojure">(ns queens
(:require [clojure.math.combinatorics :as combo]
 
(defn queens [n]
(filter (fn [x] (every? #(apply distinct? (map-indexed % x)) [+ -]))
(combo/permutations (range 1 (inc n))))) </langsyntaxhighlight>
===Backtracking as Tree processing===
Each state of the board can be represented as a sequence of the row coordinate for a queen, the column being the index in the sequence (coordinates starting at 0). Each state can have 'children' states if it is legal (no conflict) and has less than n queens. A child state is the result of adding a new queen on the next column, there are as many children states as rows as we are trying all of them. A depth first traversal of this virtual tree of states gives us the solutions when we filter out the illegal states and the incomplete states. The sequence of states is lazy so we could read only one result and not have to compute the other states.
 
<langsyntaxhighlight lang="clojure">
(defn n-queens [n]
(let[children #(map (partial conj %) (range n))
Line 2,793 ⟶ 2,924:
no-conflict?)
children []))))
</langsyntaxhighlight>
 
=={{header|CLU}}==
{{trans|C}}
<langsyntaxhighlight lang="clu">n_queens = cluster is solve
rep = null
own hist: array[int] := array[int]$[]
Line 2,855 ⟶ 2,986:
stream$putl(po, "No. " || int$unparse(count) || "\n-------\n" || s)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre style='height:50ex'>No. 1
Line 3,870 ⟶ 4,001:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# Unlike traditional N-Queens solutions that use recursion, this
# program attempts to more closely model the "human" algorithm.
Line 3,982 ⟶ 4,113:
 
nqueens(8)
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun queens (n &optional (m n))
(if (zerop n)
(list nil)
Line 4,003 ⟶ 4,134:
 
(defun print-queens (n)
(mapc #'print-solution (queens n)))</langsyntaxhighlight>
 
=== Alternate solution ===
Translation of Fortran 77
<langsyntaxhighlight lang="lisp">(defun queens1 (n)
(let ((a (make-array n))
(s (make-array n))
Line 4,046 ⟶ 4,177:
> (loop for n from 1 to 14 collect (cons n (queens1 n)))
((1 . 1) (2 . 0) (3 . 0) (4 . 2) (5 . 10) (6 . 4) (7 . 40) (8 . 92) (9 . 352)
(10 . 724) (11 . 2680) (12 . 14200) (13 . 73712) (14 . 365596))</langsyntaxhighlight>
 
As in Fortran, the iterative function above is equivalent to the recursive function below:
 
<langsyntaxhighlight lang="lisp">(defun queens2 (n)
(let ((a (make-array n))
(u (make-array (+ n n -1) :initial-element t))
Line 4,070 ⟶ 4,201:
(rotatef (aref a i) (aref a k))))))))
(sub 0))
m))</langsyntaxhighlight>
 
=={{header|Curry}}==
Three different ways of attacking the same problem. All copied from [http://web.cecs.pdx.edu/~antoy/flp/patterns/ A Catalog of Design Patterns in FLP]
<langsyntaxhighlight lang="curry">
-- 8-queens implementation with the Constrained Constructor pattern
-- Sergio Antoy
Line 4,133 ⟶ 4,264:
 
main = extend []
</syntaxhighlight>
</lang>
 
Another approach from the same source.
 
<langsyntaxhighlight lang="curry">
-- N-queens puzzle implemented with "Distinct Choices" pattern
-- Sergio Antoy
Line 4,172 ⟶ 4,303:
store = free
-- end
</syntaxhighlight>
</lang>
 
Yet another approach, also from the same source.
 
<langsyntaxhighlight lang="curry">
-- 8-queens implementation with both the Constrained Constructor
-- and the Fused Generate and Test patterns.
Line 4,236 ⟶ 4,367:
 
main = extend []
</syntaxhighlight>
</lang>
Mainly [http://www-ps.informatik.uni-kiel.de/~pakcs/webpakcs/main.cgi?queens webpakcs], uses constraint-solver.
<langsyntaxhighlight lang="curry">import CLPFD
import Findall
 
Line 4,256 ⟶ 4,387:
 
-- oneSolution = unpack $ queens 8
-- allSolutions = findall $ queens 8</langsyntaxhighlight>
 
=={{header|D}}==
===Short Version===
This high-level version uses the second solution of the Permutations task.
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, permutations2;
 
Line 4,269 ⟶ 4,400:
n.iota.map!(i => p[i] - i).array.sort().uniq.count == n)
.count.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>92</pre>
Line 4,276 ⟶ 4,407:
This version shows all the solutions.
{{trans|C}}
<langsyntaxhighlight lang="d">enum side = 8;
__gshared int[side] board;
 
Line 4,319 ⟶ 4,450:
y--;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,356 ⟶ 4,487:
===Fast Version===
{{trans|C}}
<langsyntaxhighlight lang="d">ulong nQueens(in uint nn) pure nothrow @nogc @safe
in {
assert(nn > 0 && nn <= 27,
Line 4,445 ⟶ 4,576:
immutable uint side = (args.length >= 2) ? args[1].to!uint : 8;
writefln("N-queens(%d) = %d solutions.", side, side.nQueens);
}</langsyntaxhighlight>
{{out}}
<pre>N-queens(8) = 92 solutions.</pre>
Line 4,454 ⟶ 4,585:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">/**
Return true if queen placement q[n] does not conflict with
other queens q[0] through q[n-1]
Line 4,518 ⟶ 4,649:
void main() {
enumerate(4);
}</langsyntaxhighlight>
{{out}}
<pre>* Q * *
Line 4,533 ⟶ 4,664:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program N_queens_problem;
 
Line 4,597 ⟶ 4,728:
writeln(i, ' ', x[i]);
readln;
end.</langsyntaxhighlight>
 
=={{header|Draco}}==
{{trans|C}}
<langsyntaxhighlight lang="draco">byte SIZE = 8;
word count;
 
Line 4,638 ⟶ 4,769:
count := 0;
solve(hist, 0)
corp</langsyntaxhighlight>
{{out}}
<pre>No. 1
Line 4,664 ⟶ 4,795:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
<lang>subr show_sol
subr show_sol
print "Solution " & n_sol
print "Solution " & n_sol
for iprint range n""
for writei "= 1 "to n
for j rangewrite n" "
iffor j = x[i]1 to n
write "Qif "j = x[i]
else write "Q "
write ". "else
write ". "
.
.
. print ""
print "".
print ""
.
print ""
.
subr test
ok = 1
for i range= 1 to y - 1
if x[y] = x[i] or abs (x[i] - x[y]) = abs (y - i)
ok = 0
.
.
.
n = 8
len x[] n
y = 01
x[01] = 01
while y >= 01
call test
if ok = 1 and y + 1 <>= n
y += 1
x[y] = 01
else
if ok = 1
n_sol += 1
if n_sol <= 1
call show_sol
.
.
while y >= 1 and x[y] = n
.
while y >= 0 and x[y] -= n - 1
y -= 1.
. if y >= 1
if x[y] >+= 01
x[y] += 1.
.
.
.
print n_sol & " solutions"</lang>
</syntaxhighlight>
{{out}}
<pre>Solution 1
Line 4,728 ⟶ 4,861:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; square num is i + j*N
(define-syntax-rule (sq i j) (+ i (* j N)))
Line 4,786 ⟶ 4,919:
(define (task up-to-n)
(for ((i up-to-n)) (writeln i ' ♕ (q-count i) 'solutions)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,805 ⟶ 4,938:
12 ♕ 14200 solutions
</pre>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="Ecstasy">/**
* A solver for the classic 8-queens problem.
*
* @see https://rosettacode.org/wiki/N-queens_problem
*/
module eightQueens {
void run() {
@Inject Console console;
Int count = new Board().solve(b -> console.print($"{b}\n"));
console.print($"{count} solutions found");
}
 
/**
* `Board` represents a chess board that holds only queens. The board
* is organized as columns 0 ("A") to 7 ("H"), and rows 0 (rank "1")
* to 7 (rank "8").
*/
const Board {
/**
* Construct an empty board.
*/
construct() {}
 
/**
* Internal: Construct a specifically-populated board.
*/
private construct(Int queens, Int claimed) {
this.queens = queens;
this.claimed = claimed;
}
 
/**
* Each bit of this 64-bit integer represents a queen.
*/
private Int queens;
/**
* Each bit of this 64-bit integer represents a queen or a threat.
*/
private Int claimed;
 
/**
* Translate a column and row to a bit-mask, used with the
* [queens] and [claimed] properties. Examples:
* * A1 is (0,0) => 0x0000000000000001
* * H8 is (7,7) => 0x8000000000000000
*/
private Int mask(Int col, Int row) = 1 << (row << 3) + col;
 
/**
* Determine if the specified square has a queen in it.
*/
Boolean occupied(Int col, Int row) {
return queens & mask(col, row) != 0;
}
 
/**
* Determine if the specified square is safe from the queens.
*/
Boolean safe(Int col, Int row) {
return claimed & mask(col, row) == 0;
}
 
/**
* Attempt to place a queen in a specified square.
*
* @return True iff a queen can be safely placed in the square
* @return (conditional) the new Board with the new queen on it
*/
conditional Board placeQueen(Int col, Int row) {
assert 0 <= col < 8 && 0 <= row < 8;
if (!safe(col, row)) {
return False;
}
 
Int newQueens = queens | mask(col, row);
Int newClaimed = claimed | queens;
// claim all threatened spaces
for (Int i : 0..7) {
newClaimed |= mask(i, row) | mask(col, i);
val diagDownRow = row + i - col;
if (0 <= diagDownRow < 8) {
newClaimed |= mask(i, diagDownRow);
}
val diagUpRow = row - i + col;
if (0 <= diagUpRow < 8) {
newClaimed |= mask(i, diagUpRow);
}
}
return True, new Board(newQueens, newClaimed);
}
 
/**
* Attempt to find all solutions to the n-queens problem.
*/
Int solve(function void(Board) yield) = solve(yield, 0);
 
/**
* Internal: Attempt to find all solutions to the n-queens problem,
* starting with the specified column and recursively solving by
* moving to the next column for each potential solution found in
* the specified column.
*/
private Int solve(function void(Board) yield, Int col) {
if (col == 8) {
// there is no column 8; we've found a solution
yield(this);
return 1;
}
 
Int count = 0;
for (Int rank : 8..1) {
val row = 8-rank;
if (Board afterPlacing := placeQueen(col, row)) {
count += afterPlacing.solve(yield, col + 1);
}
}
return count;
}
 
@Override String toString() {
val buf = new StringBuffer();
for (Int rank : 8..1) {
buf.append($"{rank} |");
val row = 8-rank;
for (Int col : 0..7) {
buf.add(occupied(col, row) ? 'q' : '_').add('|');
}
buf.add('\n');
}
return buf.append(" A B C D E F G H").toString();
}
}
}</syntaxhighlight>
<b>Output:</b>
<code><pre>
8 |q|_|_|_|_|_|_|_|
7 |_|_|_|_|_|_|q|_|
6 |_|_|_|_|q|_|_|_|
5 |_|_|_|_|_|_|_|q|
4 |_|q|_|_|_|_|_|_|
3 |_|_|_|q|_|_|_|_|
2 |_|_|_|_|_|q|_|_|
1 |_|_|q|_|_|_|_|_|
A B C D E F G H
 
8 |q|_|_|_|_|_|_|_|
7 |_|_|_|_|_|_|q|_|
6 |_|_|_|q|_|_|_|_|
5 |_|_|_|_|_|q|_|_|
4 |_|_|_|_|_|_|_|q|
3 |_|q|_|_|_|_|_|_|
2 |_|_|_|_|q|_|_|_|
1 |_|_|q|_|_|_|_|_|
A B C D E F G H
 
(...)
 
8 |_|_|q|_|_|_|_|_|
7 |_|_|_|_|_|q|_|_|
6 |_|_|_|q|_|_|_|_|
5 |_|q|_|_|_|_|_|_|
4 |_|_|_|_|_|_|_|q|
3 |_|_|_|_|q|_|_|_|
2 |_|_|_|_|_|_|q|_|
1 |q|_|_|_|_|_|_|_|
A B C D E F G H
 
92 solutions found
</pre></code>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
QUEENS
Line 4,876 ⟶ 5,180:
end
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,912 ⟶ 5,216:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def queen(n, display \\ true) do
solve(n, [], [], [], display)
Line 4,949 ⟶ 5,253:
Enum.each(7..12, fn n ->
IO.puts " #{n} Queen : #{RC.queen(n, false)}" # no display
end)</langsyntaxhighlight>
 
{{out}}
Line 5,082 ⟶ 5,386:
11 Queen : 2680
12 Queen : 14200
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(let ((*result* '()))
(defun grid-cnt (n)
(* n n) )
(defun x-axis (n pos)
(/ pos n) )
(defun y-axis (n pos)
(% pos n) )
(defun chess-cnt (chess-map)
(seq-count (lambda (x) x) chess-map))
(defun check-conflict (n chess-map pos)
(let ((is-conflict nil))
(cl-loop for i from 0 to (1- (grid-cnt n)) while (not is-conflict) do
(when (aref chess-map i)
(when (or (= (x-axis n i) (x-axis n pos))
(= (y-axis n i) (y-axis n pos))
(= (abs (- (x-axis n i) (x-axis n pos)))
(abs (- (y-axis n i) (y-axis n pos))))
)
(setq is-conflict 't)
)
)
)
is-conflict )
)
(defun place-chess (n chess-map start-pos)
(if (< (chess-cnt chess-map) n)
(progn
(let ()
(cl-loop for i from start-pos to (1- (grid-cnt n)) do
(when (not (aref chess-map i)) ;; check if place is empty
;; check if place is on hold by other chess
(when (not (check-conflict n chess-map i))
(let ((map1 (copy-sequence chess-map)))
(aset map1 i 't)
(place-chess n map1 i)
)
)
)
)
)
)
(progn
(if *result* (nconc *result* (list chess-map)) (setq *result* (list chess-map)))
)
)
)
 
(defun show-result (n)
(let ()
(seq-map (lambda (map1)
(let ((map-txt ""))
(message ">>>>>>>>>>>>>>")
(seq-map-indexed (lambda (elm idx)
(if (= (% idx n) 0)
;;(setq map-text (concat map-txt "\n"))
(progn
(message map-txt)
(setq map-txt "") )
)
(setq map-txt
(concat map-txt (if elm "✓" "⓪")))
) map1)
(message "<<<<<<<<<<<<<<\n")
)
) *result*)
)
(message "%d solutions in total" (length *result*))
)
(defun start-calculate (n)
(let ((chess-map (make-vector (grid-cnt n) nil)))
(place-chess n chess-map 0)
)
(show-result n)
)
 
(start-calculate 8)
)
</syntaxhighlight>
 
{{out}}
<pre>
...
92 solutions in total
</pre>
 
=={{header|Erlang}}==
Instead of spawning a new process to search for each possible solution I backtrack.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( n_queens ).
 
Line 5,170 ⟶ 5,564:
Board = solve( N ),
display( Board ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,191 ⟶ 5,585:
 
===Alternative Version===
<syntaxhighlight lang="erlang">
<lang Erlang>
%%%For 8X8 chessboard with N queens.
-module(queens).
Line 5,206 ⟶ 5,600:
(Row /= Column + N) andalso (Row /= Column - N) andalso
safe(Row, Columns, (N+1)).
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
!------------------------------------------------
! QUEENS.R : solve queens problem on a NxN board
Line 5,294 ⟶ 5,688:
END IF
END PROGRAM
</syntaxhighlight>
</lang>
Note: The program prints solutions one per line. This version works well for the PC and the C-64. For PC only you can omit the % integer-type specificator with a <code>!$INTEGER</code> pragma directive.
 
=={{header|F Sharp}}==
<langsyntaxhighlight lang="fsharp">
let rec iterate f value = seq {
yield value
Line 5,341 ⟶ 5,735:
 
printNumberOfSolutions()
</syntaxhighlight>
</lang>
 
The output:
 
<langpre>
| | | |X| | | | | |
| |X| | | | | | | |
Line 5,367 ⟶ 5,761:
10 724
11 2680
</langpre>
 
=={{header|Factor}}==
{{works with|Factor|0.98}}
<langsyntaxhighlight lang="factor">USING: kernel sequences math math.combinatorics formatting io locals ;
IN: queens
 
Line 5,397 ⟶ 5,791:
[
[ 1 + "%d " printf ] each nl
] each ;</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">variable solutions
variable nodes
 
Line 5,428 ⟶ 5,822:
solutions @ . ." solutions, " nodes @ . ." nodes" ;
 
8 queens \ 92 solutions, 1965 nodes</langsyntaxhighlight>
 
=== Alternate solution adapted from FD-V02N1.pdf ===
<syntaxhighlight lang="forth">
\ http://www.forth.org/fd/FD-V02N1.pdf
VOCABULARY nqueens ALSO nqueens DEFINITIONS
 
8 constant queens
 
\ Nqueen solution from FD-V02N1.pdf
: 1array CREATE 0 DO 1 , LOOP DOES> SWAP CELLS + ;
queens 1array a \ a,b & c: workspaces for solutions
queens 2* 1array b
queens 2* 1array c
queens 1array x \ trial solutions
 
: safe ( c i -- n )
SWAP
2DUP - queens 1- + c @ >R
2DUP + b @ >R
DROP a @ R> R> * * ;
 
: mark ( c i -- )
SWAP
2DUP - queens 1- + c 0 swap !
2DUP + b 0 swap !
DROP a 0 swap ! ;
 
: unmark ( c i -- )
SWAP
2DUP - queens 1- + c 1 swap !
2DUP + b 1 swap !
DROP a 1 swap ! ;
 
VARIABLE tries
VARIABLE sols
 
: .cols queens 0 DO I x @ 1+ 5 .r loop ;
: .sol ." Found on try " tries @ 6 .R .cols cr ;
 
: try
queens 0
DO 1 tries +!
DUP I safe
IF DUP I mark
DUP I SWAP x !
DUP queens 1- < IF DUP 1+ RECURSE ELSE sols ++ .sol THEN
DUP I unmark
THEN
LOOP DROP ;
 
: go 0 tries ! CR 0 try CR sols @ . ." solutions Found, for n = " queens . ;
go
</syntaxhighlight>
 
=={{header|Fortran}}==
Line 5,434 ⟶ 5,881:
 
Using a back tracking method to find one solution
<langsyntaxhighlight lang="fortran">program Nqueens
implicit none
 
Line 5,534 ⟶ 5,981:
write(*, "(a)") line
end subroutine
end program</langsyntaxhighlight>
{{out}} for 8, 16 and 32 queens
<pre style="height:40ex;overflow:scroll">n = 8
Line 5,658 ⟶ 6,105:
 
===Alternate Fortran 77 solution===
<langsyntaxhighlight lang="fortran">C This one implements depth-first backtracking.
C See the 2nd program for Scheme on the "Permutations" page for the
C main idea.
Line 5,730 ⟶ 6,177:
C 17 95815104
C 18 666090624
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="fortran">!The preceding program implements recursion using arrays, since Fortran 77 does not allow recursive
!functions. The same algorithm is much easier to follow in Fortran 90, using the RECURSIVE keyword.
!Like previously, the program only counts solutions. It's pretty straightforward to adapt it to print
Line 5,784 ⟶ 6,231:
print *, n, m
end do
end program</langsyntaxhighlight>
 
===Alternate Fortran 95 solution with OpenMP===
Line 5,797 ⟶ 6,244:
With some versions of GCC the function OMP_GET_WTIME is not known, which seems to be a bug. Then it's enough to comment out the two calls, and the program won't display timings.
 
<langsyntaxhighlight lang="fortran">program queens
use omp_lib
implicit none
Line 5,921 ⟶ 6,368:
go to 60
end function
end program</langsyntaxhighlight>
 
===Fortran 2008 in a Lisp-like fashion===
Line 5,928 ⟶ 6,375:
 
Part of the intent here is to show that Fortran can do quite a few things people would not think it could, if it is given adequate library support.
<langsyntaxhighlight lang="fortran">program example__n_queens
 
use, intrinsic :: iso_fortran_env, only: output_unit
Line 6,207 ⟶ 6,654:
end subroutine check_garbage
 
end program example__n_queens</langsyntaxhighlight>
{{out}}$ ./example__n_queens 1 2 3 4
<pre style="height:40ex;overflow:scroll">
Line 6,245 ⟶ 6,692:
=={{header|FreeBASIC}}==
Get slower for N > 14
<langsyntaxhighlight lang="freebasic">' version 13-04-2017
' compile with: fbc -s console
Dim Shared As ULong count, c()
Line 6,300 ⟶ 6,747:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> 1 3 5 2 4
Line 6,331 ⟶ 6,778:
=== Alternate version : recursive ===
 
<langsyntaxhighlight lang="freebasic">Sub aux(n As Integer, i As Integer, a() As Integer, _
u() As Integer, v() As Integer, ByRef m As LongInt)
 
Line 6,371 ⟶ 6,818:
aux(n, 1, a(), u(), v(), m)
Print m
End If</langsyntaxhighlight>
 
=== Alternate version : iterative ===
 
<langsyntaxhighlight lang="freebasic">Dim As Integer n, i, j, k, p, q
Dim m As LongInt = 0
 
Line 6,417 ⟶ 6,864:
u(p) = 1 : v(q) = 1
Goto L3
End If</langsyntaxhighlight>
 
=={{header|Frink}}==
This example uses Frink's built-in <CODE>array.permute[]</CODE> method to generate possible permutations of the board efficiently.
<langsyntaxhighlight Frinklang="frink">solution[board] :=
{
for q = 0 to length[board] - 1
Line 6,432 ⟶ 6,879:
for b = array[1 to 8].permute[]
if solution[b]
println[b]</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/N-queens_problem}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
The following function:
In '''[https://formulae.org/?example=N-queens_problem this]''' page you can see the program(s) related to this task and their results.
 
* Is able to calculate solution for chessboards of any size (but it is slow for big chessboards)
* It does not detect rotated or reflected solutions
 
This is an example of backtracking:
 
[[File:Fōrmulæ - N-queens problem 01.png]]
 
[[File:Fōrmulæ - N-queens problem 02.png]]
 
[[File:Fōrmulæ - N-queens problem 03.png]]
 
'''Improvement.''' The following functions calls the previous one, but shows the solution on a more friendly way
 
[[File:Fōrmulæ - N-queens problem 04.png]]
 
[[File:Fōrmulæ - N-queens problem 05.png]]
 
[[File:Fōrmulæ - N-queens problem 06.png]]
 
=={{header|GAP}}==
Line 6,446 ⟶ 6,912:
Translation of Fortran 77. See also alternate Python implementation. One function to return the number of solutions, another to return the list of permutations.
 
<langsyntaxhighlight lang="gap">NrQueens := function(n)
local a, up, down, m, sub;
a := [1 .. n];
Line 6,523 ⟶ 6,989:
[ 0, 0, 0, 0, 0, 0, 1, 0 ],
[ 0, 1, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 1, 0, 0, 0, 0 ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
===Niklaus Wirth algorithm (Wikipedia)===
<langsyntaxhighlight lang="go">// A fairly literal translation of the example program on the referenced
// WP page. Well, it happened to be the example program the day I completed
// the task. It seems from the WP history that there has been some churn
Line 6,587 ⟶ 7,053:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 6,602 ⟶ 7,068:
 
=== Refactored Niklaus Wirth algorithm (clearer/Go friendly solution) ===
<langsyntaxhighlight lang="go">/*
* N-Queens Problem
*
Line 6,725 ⟶ 7,191:
trycol(0)
printresults()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,746 ⟶ 7,212:
[[N-queens_problem/dlx_go|dlx packge]].
 
<langsyntaxhighlight Golang="go">package main
 
import (
Line 6,881 ⟶ 7,347:
}
return nil
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,915 ⟶ 7,381:
===Distinct Solutions===
This solver starts with the N! distinct solutions to the N-Rooks problem and then keeps only the candidates in which all Queens are mutually diagonal-safe.
<langsyntaxhighlight lang="groovy">def listOrder = { a, b ->
def k = [a.size(), b.size()].min()
def i = (0..<k).find { a[it] != b[it] }
Line 6,938 ⟶ 7,404:
// each permutation is an N-Rooks solution
orderedPermutations((0..<n)).findAll (diagonalSafe)
}</langsyntaxhighlight>
 
===Unique Solutions===
Unique solutions are equivalence classes of distinct solutions, factoring out all reflections and rotations of a given solution. See the [[WP:Eight_queens_puzzle|Wikipedia page]] for more details.
<langsyntaxhighlight lang="groovy">class Reflect {
public static final diag = { list ->
final n = list.size()
Line 6,992 ⟶ 7,458:
}
qus
}</langsyntaxhighlight>
 
===Test and Results===
This script tests both distinct and unique solution lists.
<langsyntaxhighlight lang="groovy">(1..9).each { n ->
def qds = queensDistinctSolutions(n)
def qus = queensUniqueSolutions(qds)
Line 7,003 ⟶ 7,469:
else { println "first:${qus[0]}"; println "last:${qus[-1]}" }
println()
}</langsyntaxhighlight>
 
Interpreting the Results:
Line 7,073 ⟶ 7,539:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad
import Data.List
 
Line 7,102 ⟶ 7,568:
 
-- prints all the solutions for 6 queens
main = mapM_ printSolution $ queens 6</langsyntaxhighlight>
 
If you just want one solution, simply take the <code>head</code> of the result of <code>queens n</code>; since Haskell is lazy, it will only do as much work as needed to find one solution and stop.
 
===Alternative version===
<langsyntaxhighlight lang="haskell">import Control.Monad (foldM)
import Data.List ((\\))
 
Line 7,117 ⟶ 7,583:
where
f qs _ = [q:qs | q <- [1..n] \\ qs, q `notDiag` qs]
q `notDiag` qs = and [abs (q - qi) /= i | (qi,i) <- qs `zip` [1..]]</langsyntaxhighlight>
 
===Using permutations===
This version uses permutations to generate unique horizontal and vertical position for each queen. Thus, we only need to check diagonals. However, it is less efficient than the previous version because it does not prune out prefixes that are found to be unsuitable.
<langsyntaxhighlight lang="haskell">import Data.List (nub, permutations)
 
-- checks if queens are on the same diagonal
Line 7,132 ⟶ 7,598:
 
-- 8 is for "8 queens"
main = print $ generate 8</langsyntaxhighlight>
 
===In terms of foldr===
A back-tracking variant using the Prelude's plain '''foldr''':
{{Trans|JavaScript}}
<langsyntaxhighlight lang="haskell">import Data.List (intercalate, transpose)
 
--------------------- N QUEENS PROBLEM -------------------
Line 7,190 ⟶ 7,656:
 
main :: IO ()
main = (putStrLn . unlines) $ showSolutions 10 7</langsyntaxhighlight>
{{Out}}
<pre>......♛ ......♛ ......♛ ......♛ .....♛. .....♛. .....♛. .....♛. .....♛. .....♛.
Line 7,225 ⟶ 7,691:
 
===Breadth-first search and Depth-first search===
<langsyntaxhighlight lang="haskell">import Control.Monad
import System.Environment
 
Line 7,287 ⟶ 7,753:
let n = read narg :: Int
print (bfs n [emptySt])
print (head $ dfs n emptySt)</langsyntaxhighlight>
 
{{Out}}
Line 7,294 ⟶ 7,760:
 
=={{header|Heron}}==
<langsyntaxhighlight lang="heron">module NQueens {
inherits {
Heron.Windows.Console;
Line 7,388 ⟶ 7,854:
}
}
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Here's a solution to the <tt>n = 8</tt> case:
<langsyntaxhighlight lang="icon">procedure main()
write(q(1), " ", q(2), " ", q(3), " ", q(4), " ", q(5), " ", q(6), " ", q(7), " ", q(8))
end
Line 7,407 ⟶ 7,873:
every 0 = row[r := 1 to 8] = ddiag[r + c - 1] = udiag[8 + r - c] do # test if free
suspend row[r] <- ddiag[r + c - 1] <- udiag[8 + r - c] <- r # place and yield
end</langsyntaxhighlight>
 
Notes:
Line 7,418 ⟶ 7,884:
* As the calls to q() are evaluated in main, each one will suspend a possible row, thereby allowing the next q(n) in main to be evaluated. If any of the q() fails to yield a row for the nth queen (or runs out of solutions) the previous, suspended calls to q() are backtracked progressively. If the final q(8) yields a row, the write() will be called with the row positions of each queen. Note that even the final q(8) will be suspended along with the other 7 calls to q(). Unless the write() is driven to produce more solutions (see next point) the suspended procedures will be closed at the "end of statement" ie after the write has "succeeded".
* If you want to derive all possible solutions, main() can be embellished with the '''every''' keyword:
<langsyntaxhighlight lang="icon">
procedure main()
every write(q(1), " ", q(2), " ", q(3), " ", q(4), " ", q(5), " ", q(6), " ", q(7), " ", q(8))
end
</syntaxhighlight>
</lang>
This drives the backtracking to find more solutions.
 
Line 7,430 ⟶ 7,896:
The comment explains how to modify the program to produce <i>all</i>
solutions for a given <tt>N</tt>.
<langsyntaxhighlight lang="icon">global n, rw, dd, ud
 
procedure main(args)
Line 7,464 ⟶ 7,930:
write()
return # Comment out to see all possible solutions
end</langsyntaxhighlight>
 
A sample run for <tt>N = 6</tt>:
Line 7,488 ⟶ 7,954:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "NQueens.bas"
110 TEXT 80
120 DO
Line 7,525 ⟶ 7,991:
450 LET T(I)=1
460 NEXT
470 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
Line 7,531 ⟶ 7,997:
This is one of several J solutions shown and explained on this [[J:Essays/N%20Queens%20Problem|J wiki page]]
 
<langsyntaxhighlight lang="j">perm =: ! A.&i. ] NB. all permutations of integers 0 to y
comb2 =: (, #: I.@,@(</)&i.)~ NB. all size 2 combinations of integers 0 to y
mask =: [ */@:~:&(|@-/) {
queenst=: comb2 (] #"1~ mask)&.|: perm</langsyntaxhighlight>
 
Note that the Roger Hui's approach (used here) matches the description attributed to Raymond Hettinger (in the Python implementation). (Both were posted years ago: 1981 for Hui's version which was used here, and 2009 for Hettinger's.) However they do use different diagonal queen clash elimination approaches -see [http://rosettacode.org/wiki/N-queens_problem#Roger_Hui_.281981.29_Algorithm C# Roger Hui Algorithm] for a comparison of the two approaches.
Line 7,540 ⟶ 8,006:
Example use:
 
<langsyntaxhighlight lang="j"> $queenst 8
92 8</langsyntaxhighlight>
 
92 distinct solutions for an 8 by 8 board.
 
<langsyntaxhighlight lang="j"> {.queenst 8
0 4 7 5 2 6 1 3</langsyntaxhighlight>
 
One of the solutions. Position indicates row number, the integer indicates column number (0..7) for each queen -- though of course you could just as validly think of that the other way around.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class NQueens {
 
private static int[] b = new int[8];
Line 7,598 ⟶ 8,064:
}
}
}</langsyntaxhighlight>
 
=={{header|Javascript}}==
===ES5===
Algorithm uses recursive Backtracking. Checks for correct position on subfields, whichs saves a lot position checks. Needs 15.720 position checks for a 8x8 field.
<langsyntaxhighlight lang="javascript">function queenPuzzle(rows, columns) {
if (rows <= 0) {
return [[]];
Line 7,635 ⟶ 8,101:
}
 
console.log(queenPuzzle(8,8));</langsyntaxhighlight>
 
===ES6===
Translating the ES5 version, and adding a function to display columns of solutions.
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 7,767 ⟶ 8,233:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>....... ....... ....... ....... ♛...... ♛...... ♛...... ♛...... ♛...... ♛......
Line 7,806 ⟶ 8,272:
This section presents a function for finding a single solution using
the formulae for explicit solutions at [[WP:Eight_queens_puzzle|Eight Queens Puzzle]].
<langsyntaxhighlight lang="jq">def single_solution_queens(n):
def q: "♛";
def init(k): reduce range(0;k) as $i ([]; . + ["."]);
Line 7,830 ⟶ 8,296:
(""; reduce $row[] as $x (.; . + $x) + "\n");
 
single_solution_queens(8) | pp</langsyntaxhighlight>
{{out}}
$ jq -M -n -r -f n-queens-single-solution.jq
<langsyntaxhighlight lang="sh">...♛....
.....♛..
.......♛
Line 7,840 ⟶ 8,306:
♛.......
..♛.....
....♛...</langsyntaxhighlight>
====Generate-and-test counter====
{{ works with|jq|1.4}}
'''Part 1: Generic functions'''
<langsyntaxhighlight lang="jq"># permutations of 0 .. (n-1)
def permutations(n):
# Given a single array, generate a stream by inserting n at different positions:
Line 7,856 ⟶ 8,322:
end;
 
def count(g): reduce g as $i (0; .+1);</langsyntaxhighlight>
'''Part 2: n-queens'''
<langsyntaxhighlight lang="jq">def queens(n):
def sums:
. as $board
Line 7,874 ⟶ 8,340:
 
count( permutations(n) | select(allowable) );
</syntaxhighlight>
</lang>
'''Example''':
<syntaxhighlight lang ="jq">queens(8)</langsyntaxhighlight>
{{out}}
92
Line 7,882 ⟶ 8,348:
=={{header|Julia}}==
 
<langsyntaxhighlight lang="ruby">"""
# EightQueensPuzzle
 
Line 7,949 ⟶ 8,415:
println()
end
</langsyntaxhighlight> {{out}}
<pre>
n = 1
Line 8,022 ⟶ 8,488:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
var count = 0
Line 8,051 ⟶ 8,517:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 8,112 ⟶ 8,578:
=={{header|Liberty BASIC}}==
Program uses permutation generator (stores all permutations) and solves tasks 4x4 to 9x9. It prints all the solutions.
<syntaxhighlight lang="lb">
<lang lb>
'N queens
'>10 would not work due to way permutations used
Line 8,198 ⟶ 8,664:
End Function
 
</syntaxhighlight>
</lang>
 
=={{header|Locomotive Basic}}==
Line 8,204 ⟶ 8,670:
Uses the heuristic from the Wikipedia article to get one solution.
 
<langsyntaxhighlight lang="locobasic">10 mode 1:defint a-z
20 while n<4:input "How many queens (N>=4)";n:wend
30 dim q(n),e(n),o(n)
Line 8,255 ⟶ 8,721:
500 for i=1 to n
510 if o(i)=1 or o(i)=3 then o(i)=-1 else if o(i)=0 then o(i)=1:o(i+1)=3:return
520 next</langsyntaxhighlight>
 
[[File:Queens Puzzle, Locomotive Basic.png]]
Line 8,261 ⟶ 8,727:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to try :files :diag1 :diag2 :tried
if :files = 0 [make "solutions :solutions+1 show :tried stop]
localmake "safe (bitand :files :diag1 :diag2)
Line 8,277 ⟶ 8,743:
end
 
print queens 8 ; 92</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">N = 8
 
-- We'll use nil to indicate no queen is present.
Line 8,314 ⟶ 8,780:
else
print(string.format("No solution for %d queens.\n", N))
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
{{trans|VBA}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module N_queens {
Const l = 15 'number of queens
Line 8,377 ⟶ 8,843:
}
N_queens
</syntaxhighlight>
</lang>
 
=={{header|m4}}==
Line 8,383 ⟶ 8,849:
It finds one solution of the Eight Queens problem.
 
<langsyntaxhighlight lang="m4">divert(-1)
 
The following macro find one solution to the eight-queens problem:
Line 8,476 ⟶ 8,942:
divert`'dnl
dnl
solve_eight_queens</langsyntaxhighlight>
 
{{out}}
Line 8,501 ⟶ 8,967:
{{trans|Python}}
 
<langsyntaxhighlight lang="maple">queens:=proc(n)
local a,u,v,m,aux;
a:=[$1..n];
Line 8,534 ⟶ 9,000:
end:
 
for a in queens(8) do printf("%a\n",a) od;</langsyntaxhighlight>
 
{{out}}
Line 8,548 ⟶ 9,014:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This code recurses through the possibilities, using the "safe" method to check if the current set is allowed. The recursive method has the advantage that finding all possibilities is about as hard (code-wise, not computation-wise) as finding just one.
<langsyntaxhighlight Mathematicalang="mathematica">safe[q_List, n_] :=
With[{l = Length@q},
Length@Union@q == Length@Union[q + Range@l] ==
Line 8,556 ⟶ 9,022:
If[Length[q] == n, {q},
Cases[nQueen[Append[q, #], n] & /@ Range[n],
Except[{Null} | {}], {2}]], Null]</langsyntaxhighlight>
 
This returns a list of valid permutations by giving the queen's column number for each row. It can be displayed in a list of chess-board tables like this:
<langsyntaxhighlight Mathematicalang="mathematica">matrixView[n_] :=
Grid[Normal@
SparseArray[MapIndexed[{#, First@#2} -> "Q" &, #], {n, n}, "."],
Frame -> All] & /@ nQueen[n]
matrixView[6] // OutputForm</langsyntaxhighlight>
{{out}}
<pre>{. . . Q . ., . . . . Q ., . Q . . . ., . . Q . . .}
Line 8,580 ⟶ 9,046:
This solution uses Permutations and subsets, also prints out a board representation.
 
<langsyntaxhighlight Mathematicalang="mathematica">n=8;cnt=1;per=Permutations[Range[n],{n}];(* All Permutations of length n *)
Do[per[[q]]=Partition[Riffle[Reverse[Range[n]],per[[q]]],2],{q,1,Length[per]}];(* Riffled in the reverse of [range n] partitioned into pairs*)
Do[w=Subsets[per[[t]],{2}];(* This is a full subset of the previous set of pairs taken 2 at a time *)
Line 8,587 ⟶ 9,053:
If[tot==0,g=Grid[Table[" ",{n},{n}],Alignment->Center,Frame->All,Spacings->{1.2,1}];(* If no clashing diagonals setup an array and print the permutation and the grid*)
Do[g[[1,per[[t,w,1]],per[[t,w,2]]]]="Q",{w,1,n}];
Print[cnt," ",per[[t]]," ",g];cnt++],{t,1,Length[per]}]</langsyntaxhighlight>
 
Alternative Solution using Linear Programming:
 
<syntaxhighlight lang="mathematica">
<lang Mathematica>
dispSol[sol_] := sol /. {1 -> "Q" , 0 -> "-"} // Grid
 
Line 8,636 ⟶ 9,102:
 
solveNqueens[8] // dispSol
</syntaxhighlight>
</lang>
<pre>- - - - Q - - -
- Q - - - - - -
Line 8,648 ⟶ 9,114:
=={{header|MATLAB}}==
This solution is inspired by Raymond Hettinger's permutations based solution which was made in Python: https://code.activestate.com/recipes/576647/
<syntaxhighlight lang="matlab">n=8;
<lang MATLAB>n=8;
solutions=[[]];
v = 1:n;
Line 8,672 ⟶ 9,138:
end
s
end</langsyntaxhighlight>
{{out}}
<pre>
Line 8,688 ⟶ 9,154:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* translation of Fortran 77, return solutions as permutations */
 
queens(n) := block([a, i, j, m, p, q, r, s, u, v, w, y, z],
Line 8,705 ⟶ 9,171:
[1, 6, 8, 3, 7, 4, 2, 5],
...]] */
length(%); /* 92 */</langsyntaxhighlight>
 
<syntaxhighlight lang="maxima">
/* Inspired by code from Python */
Queens(N):=block([K,C,P,V,L:[]],
C: makelist(K,K,1,N),
P: permutations(C),
for V in P do (
if is(N=length(unique(makelist(V[K]+K, K, C)))) then (
if is(N=length(unique(makelist(V[K]-K, K, C)))) then (
L: endcons(V, L)
)
)
), L
)$
 
Queens(8);length(%);</syntaxhighlight>
 
=={{header|MiniScript}}==
This GUI implementation is for use with [http://miniscript.org/MiniMicro Mini Micro]. It displays a chess board with animation of the possibilities. At the end, after all of the solutions have been calculated, you can scroll through them with the left/right cursor keys.
<syntaxhighlight lang="miniscript">
clear
N = 8
SOLUTIONCOUNT = 0
 
getTileDisplay = function
gfx.clear
queen = file.loadImage("/sys/pics/gamePieces/blackQueen.png")
gfx.color = color.white
gfx.fillRect 0, 0, 80, 80
gfx.fillRect 160, 0, 80, 80
gfx.color = color.brown
gfx.fillRect 80, 0, 80, 80
gfx.fillRect 240, 0, 80, 80
gfx.drawImage queen, 172, 14
gfx.drawImage queen, 252, 14
tiles = gfx.getImage(0,0, 320, 80)
gfx.clear
display(4).mode = displayMode.tile
td = display(4)
td.cellSize = 640 / N
td.extent = [N, N]
td.overlap = 0
td.tileSet = tiles
td.tileSetTileSize = 80
td.scrollX = -160
td.clear
return td
end function
 
updateBoard = function(td, arr)
for y in range(0, N - 1)
ix = y % 2
for x in range(0, N - 1)
td.setCell x, y, ix
ix += 1
ix %= 2
end for
end for
y = 0
for x in arr
td.setCell x, y, td.cell(x, y) + 2
y += 1
end for
yield
end function
 
list.has = function(n)
return self.indexOf(n) != null
end function
 
queens = function(n, i, a, b, c, td)
solutions = []
updateBoard(td, a)
if i < n then
for j in range(0, n - 1)
if not a.has(j) and not b.has(i + j) and not c.has(i - j) then
solution = queens(n, i + 1, a + [j], b + [i + j], c + [i - j], td)
if solution != null then solutions += solution
end if
end for
else
globals.SOLUTIONCOUNT += 1
text.row = 25
text.print "SOLUTIONS"
text.print globals.SOLUTIONCOUNT
solutions.push(a)
end if
return solutions
end function
 
td = getTileDisplay
solutions = queens(N, 0, [], [], [], td)
ix = 0
while true
text.row = 25
text.print "SOLUTION # "
text.print (ix + 1) + (" " * 10)
text.print
text.print char(17) + "/" + char(18) + " keys"
updateBoard(td, solutions[ix])
k = key.get
kcode = code(k)
if kcode == 27 then break
ix = ix - (kcode == 17) + (kcode == 18) + solutions.len
ix %= solutions.len
end while
</syntaxhighlight>
 
=={{header|MiniZinc}}==
<langsyntaxhighlight lang="minizinc">int: n;
array [1..n] of var 1..n: q; % queen in column i is in row q[i]
 
Line 8,721 ⟶ 9,296:
satisfy;
output [ if fix(q[j]) == i then "Q" else "." endif ++
if j == n then "\n" else "" endif | i,j in 1..n]</langsyntaxhighlight>
 
This solution appears in the official MiniZinc tutorial documentation, and is generalized.
Line 8,727 ⟶ 9,302:
=={{header|Modula-2}}==
{{trans|C}}
<langsyntaxhighlight lang="modula2">MODULE NQueens;
FROM InOut IMPORT Write, WriteCard, WriteString, WriteLn;
 
Line 8,782 ⟶ 9,357:
count := 0;
Solve(N, 0);
END NQueens.</langsyntaxhighlight>
 
{{out}}
Line 9,799 ⟶ 10,374:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">Queens New count,flip,row,sol
Set sol=0
For row(1)=1:1:4 Do try(2) ; Not 8, the other 4 are symmetric...
Line 9,858 ⟶ 10,433:
Quit
Do Queens
</syntaxhighlight>
</lang>
<div style="overflow:scroll; height:400px;">
<syntaxhighlight lang="mumps">
<lang MUMPS>
+--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+
8 | |##| Q|##| |##| |##| | |##| Q|##| |##| |##| | |##| | Q| |##| |##|
Line 10,068 ⟶ 10,643:
1 |##| |##| | Q| |##| |
+--+--+--+--+--+--+--+--+
A B C D E F G H</langsyntaxhighlight></div>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">const BoardSize = 8
 
proc underAttack(col: int; queens: seq[int]): bool =
Line 10,099 ⟶ 10,674:
if row > 0: stdout.write ' '
stdout.write chr(ord('a') + row), col
stdout.write if i mod 4 == 3: "\n" else: " "</langsyntaxhighlight>
 
{{out}}
Line 10,131 ⟶ 10,706:
{{trans|Java}}
 
<langsyntaxhighlight lang="objeck">bundle Default {
class NQueens {
b : static : Int[];
Line 10,188 ⟶ 10,763:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
{{libheader|FaCiLe}}
 
<langsyntaxhighlight lang="ocaml">(* Authors: Nicolas Barnier, Pascal Brisset
Copyright 2004 CENA. All rights reserved.
This code is distributed under the terms of the GNU LGPL *)
Line 10,251 ⟶ 10,826:
then raise (Failure "Usage: queens <nb of queens>");
Gc.set ({(Gc.get ()) with Gc.space_overhead = 500}); (* May help except with an underRAMed system *)
queens (int_of_string Sys.argv.(1));;</langsyntaxhighlight>
===A stand-alone OCaml solution===
<langsyntaxhighlight lang="ocaml">let solutions n =
 
let show board =
Line 10,284 ⟶ 10,859:
else 8 in
 
solutions n</langsyntaxhighlight>
{{out}}
<pre>$ ocaml queens.ml 6
Line 10,318 ⟶ 10,893:
=={{header|Oz}}==
A pretty naive solution, using constraint programming:
<langsyntaxhighlight lang="oz">declare
fun {Queens N}
proc {$ Board}
Line 10,385 ⟶ 10,960:
in
{Length Solutions} = 92 %% assert
{Inspect {List.take Solutions 3}}</langsyntaxhighlight>
 
There is a more concise and much more efficient [http://www.mozart-oz.org/documentation/fdt/node25.html#section.scripts.queens solution] in the Mozart documentation.
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program queens;
 
const l=16;
Line 10,470 ⟶ 11,045:
14 365596
15 2279184
16 14772512 }</langsyntaxhighlight>
 
===Alternative===
Line 10,488 ⟶ 11,063:
Solution found</pre>
<langsyntaxhighlight lang="pascal">program NQueens;
{$IFDEF FPC}
{$MODE DELPHI}
Line 10,599 ⟶ 11,174:
end;
WriteLn('Fertig');
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 10,623 ⟶ 11,198:
 
=={{header|PDP-11 Assembly}}==
<syntaxhighlight lang="pdp-11 assembly">
<lang PDP-11 Assembly>
; "eight queens problem" benchmark test
 
Line 10,738 ⟶ 11,313:
 
scr: ;display RAM
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my ($board_size, @occupied, @past, @solutions);
 
sub try_column {
Line 10,780 ⟶ 11,355:
 
#print for @solutions; # un-comment to see all solutions
print "total " . @solutions . " solutions\n";</langsyntaxhighlight>
{{out}}
<pre>total 14200 solutions</pre>
 
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<syntaxhighlight lang="phix">
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
with javascript_semantics
<span style="color: #000080;font-style:italic;">--
--
-- demo\rosetta\n_queens.exw
-- demo\rosetta\n_queens.exw
-- =========================
-- =========================
--</span>
--
<span style="color: #004080;">sequence</span> <span style="color: #000000;">co</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- columns occupied
sequence co, -- columns occupied
-- (ro is implicit)</span>
-- (ro is implicit)
<span style="color: #000000;">fd</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- forward diagonals</span>
fd, -- forward diagonals
<span style="color: #000000;">bd</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- backward diagonals</span>
bd, <span style="color: #000000;">board</span> -- backward diagonals
board
<span style="color: #004080;">atom</span> <span style="color: #000000;">count</span>
atom count
<span style="color: #008080;">procedure</span> <span style="color: #000000;">solve</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">)</span>
procedure solve(integer row, integer N, integer show)
<span style="color: #008080;">for</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">do</span>
for col=1 to N do
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">co</span><span style="color: #0000FF;">[</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
if not co[col] then
<span style="color: #004080;">integer</span> <span style="color: #000000;">fdi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">col</span><span style="color: #0000FF;">+</span><span style="color: #000000;">row</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
integer fdi = col+row-1,
<span style="color: #000000;">bdi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">-</span><span style="color: #000000;">col</span><span style="color: #0000FF;">+</span><span style="color: #000000;">N</span>
bdi = row-col+N
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">fd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdi</span><span style="color: #0000FF;">]</span>
if not fd[fdi]
<span style="color: #008080;">and</span> <span style="color: #008080;">not</span> <span style="color: #000000;">bd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">bdi</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
and not bd[bdi] then
<span style="color: #000000;">board</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">][</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'Q'</span>
board[row][col] = 'Q'
<span style="color: #000000;">co</span><span style="color: #0000FF;">[</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
co[col] = true
<span style="color: #000000;">fd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
fd[fdi] = true
<span style="color: #000000;">bd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">bdi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
bd[bdi] = true
<span style="color: #008080;">if</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">=</span><span style="color: #000000;">N</span> <span style="color: #008080;">then</span>
if row=N then
<span style="color: #008080;">if</span> <span style="color: #000000;">show</span> <span style="color: #008080;">then</span>
if show then
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">board</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
puts(1,join(board,"\n")&"\n")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'='</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span styleputs(1,repeat('=',N)&"color: #008080;\n">if</span>)
end if
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style count +="color: #008080;">else</span>1
else
<span style="color: #000000;">solve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">row</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">,</span><span style="color: #000000;">show</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>solve(row+1,N,show)
end if
<span style="color: #000000;">board</span><span style="color: #0000FF;">[</span><span style="color: #000000;">row</span><span style="color: #0000FF;">][</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'.'</span>
board[row][col] = '.'
<span style="color: #000000;">co</span><span style="color: #0000FF;">[</span><span style="color: #000000;">col</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
co[col] = false
<span style="color: #000000;">fd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
fd[fdi] = false
<span style="color: #000000;">bd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">bdi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
bd[bdi] = false
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
end procedure
<span style="color: #008080;">procedure</span> <span style="color: #000000;">n_queens</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">=</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
procedure n_queens(integer N=8, integer show=1)
<span style="color: #000000;">co</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
co = repeat(false,N)
<span style="color: #000000;">fd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
fd = repeat(false,N*2-1)
<span style="color: #000000;">bd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
bd = repeat(false,N*2-1)
<span style="color: #000000;">board</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'.'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">),</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
board = repeat(repeat('.',N),N)
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
count = 0
<span style="color: #000000;">solve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">,</span><span style="color: #000000;">show</span><span style="color: #0000FF;">)</span>
solve(1,N,show)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d queens: %d solutions\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">N</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span><span style="color: #0000FF;">})</span>
printf(1,"%d queens: %d solutions\n",{N,count})
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
end procedure
<span style="color: #008080;">for</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">12</span><span style="color: #0000FF;">:</span><span style="color: #000000;">14</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for N=1 to iff(platform()=JS?12:14) do
<span style="color: #000000;">n_queens</span><span style="color: #0000FF;">(</span><span style="color: #000000;">N</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;"><</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
n_queens(N,N<5)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<!--</lang>-->
</syntaxhighlight>
{{out}}
<pre>
Line 10,874 ⟶ 11,450:
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
<html>
<head>
Line 11,052 ⟶ 11,628:
</body>
</html>
</syntaxhighlight>
</lang>
 
<h2>Solution with recursion</h2>
 
<syntaxhighlight lang="php">
<lang PHP>
<html>
<body>
Line 11,130 ⟶ 11,706:
</body>
</html>
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
===0/1 encoding a N x N matrix===
Using constraint modelling using an 0/1 encoding of an N x N matrix. It is the probably the fastest approach when using SAT and MIP solvers.
<langsyntaxhighlight Picatlang="picat">import sat.
% import mip.
 
Line 11,157 ⟶ 11,733:
sum([Q[I,J] : I in 1..N]) #= 1
end,
solve([inout],Q).</langsyntaxhighlight>
 
===Constraint programming===
This is the "standard" model using constraint programming (in contract to the SAT 0/1 approach). Instead of an NxN matrix, this encoding uses a single list representing the columns. The three <code>all_different/1</code> then ensures that the rows, and the two diagonals are distinct.
<langsyntaxhighlight Picatlang="picat">import cp.
 
queens(N, Q) =>
Line 11,169 ⟶ 11,745:
all_different([$Q[I]-I : I in 1..N]),
all_different([$Q[I]+I : I in 1..N]),
solve([ff],Q).</langsyntaxhighlight>
 
==="Naive" approach===
This approach might be called "naive" (in the constraint programming context) since it doesn't use the (general) faster <code>all_different/1</code> constraint.
<langsyntaxhighlight Picatlang="picat">queens_naive(N, Q) =>
Q = new_list(N),
Q :: 1..N,
Line 11,181 ⟶ 11,757:
Q[I] - I #!= Q[J] - J
end,
solve([ff], Q).</langsyntaxhighlight>
 
 
Line 11,222 ⟶ 11,798:
=={{header|PicoLisp}}==
===Calling 'permute'===
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l") # for 'permute'
 
(de queens (N)
Line 11,232 ⟶ 11,808:
(length (uniq (mapcar - L R))) )
(inc 'Cnt) ) )
Cnt ) )</langsyntaxhighlight>
===Permuting inline===
This alternative version does not first pre-generate all permutations with
'permute', but creates them recursively. Also, it directly checks for
duplicates, instead of calling 'uniq' and 'length'. This is much faster.
<langsyntaxhighlight PicoLisplang="picolisp">(de queens (N)
(let (R (range 1 N) L (copy R) X L Cnt 0)
(recur (X) # Permute
Line 11,252 ⟶ 11,828:
(mapcar - L R) )
(inc 'Cnt) ) ) )
Cnt ) )</langsyntaxhighlight>
{{out}} for both cases:
<pre>: (queens 8)
Line 11,259 ⟶ 11,835:
=={{header|PL/I}}==
This code compiles with PL/I compilers ranging from the ancient IBM MVT PL/I F compiler of the 1960s, the IBM PL/I Optimizing compiler, thru the IBM PL/I compiler for MVS and VM, to the z/OS Enterprise PL/I v4.60 compiler;spanning 50 years of PL/I compilers. It only outputs the number of solutions found for a given N instead of printing out each individual chess board solution to avoid filling up spool space for large values of N. It's trivial to add a print-out of the individual solutions.
<langsyntaxhighlight lang="pli">
NQUEENS: PROC OPTIONS (MAIN);
DCL A(35) BIN FIXED(31) EXTERNAL;
Line 11,337 ⟶ 11,913:
END QUEEN;
END NQUEENS; </langsyntaxhighlight>
 
=={{header|PowerBASIC}}==
=== Recursive version ===
{{trans|Stata}}
<langsyntaxhighlight lang="powerbasic">#COMPILE EXE
#DIM ALL
 
Line 11,387 ⟶ 11,963:
PRINT m
END IF
END FUNCTION</langsyntaxhighlight>
 
=== Iterative version ===
{{trans|Stata}}
<langsyntaxhighlight lang="powerbasic">#COMPILE EXE
#DIM ALL
 
Line 11,437 ⟶ 12,013:
GOTO 3
END IF
END FUNCTION</langsyntaxhighlight>
 
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function PlaceQueen ( [ref]$Board, $Row, $N )
{
Line 11,501 ⟶ 12,077:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-NQueensBoard 8
''
Line 11,510 ⟶ 12,086:
''
Get-NQueensBoard 14
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 11,547 ⟶ 12,123:
=={{header|Processing}}==
{{trans|Java}}
<langsyntaxhighlight lang="java">
int n = 8;
int[] b = new int[n];
Line 11,618 ⟶ 12,194:
b[0] = -1;
}
</syntaxhighlight>
</lang>
 
==={{header|Processing Python mode}}===
Line 11,625 ⟶ 12,201:
This solution, originally by Raymond Hettinger for demonstrating the power of the itertools module, generates all solutions.
 
<langsyntaxhighlight lang="python">from itertools import permutations, product
 
n = 8
Line 11,653 ⟶ 12,229:
global i
i = (i + 1) % len(solutions)
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Line 11,659 ⟶ 12,235:
 
Solution #1:
<langsyntaxhighlight Prologlang="prolog">solution([]).
solution([X/Y|Others]) :-
Line 11,679 ⟶ 12,255:
member(Item,Rest).
template([1/Y1,2/Y2,3/Y3,4/Y4,5/Y5,6/Y6,7/Y7,8/Y8]).</langsyntaxhighlight>
 
Solution #2:
<langsyntaxhighlight Prologlang="prolog">solution(Queens) :-
permutation([1,2,3,4,5,6,7,8], Queens),
safe(Queens).
Line 11,709 ⟶ 12,285:
Y-Y1=\=Xdist,
Dist1 is Xdist + 1,
noattack(Y,Ylist,Dist1).</langsyntaxhighlight>
 
Solution #3:
<langsyntaxhighlight Prologlang="prolog">solution(Ylist) :-
sol(Ylist,[1,2,3,4,5,6,7,8],
[1,2,3,4,5,6,7,8],
Line 11,731 ⟶ 12,307:
del(Item,[First|List],[First|List1]) :-
del(Item,List,List1).</langsyntaxhighlight>
 
[http://ideone.com/Y6olN Output]:
Line 11,739 ⟶ 12,315:
===Alternative version===
Uses non-ISO predicates between/3 and select/3 (available in SWI Prolog and GNU Prolog).
<langsyntaxhighlight lang="prolog">:- initialization(main).
 
 
Line 11,754 ⟶ 12,330:
 
 
main :- findall(Qs, (queens(8,Qs), write(Qs), nl), _), halt.</langsyntaxhighlight>
[http://ideone.com/3bbIx0 Runs in: time: 0.02 memory: 68352]
 
Line 11,760 ⟶ 12,336:
Uses backtracking- a highly efficient mechanism in Prolog to find all solutions.
{{works with|SWI Prolog|version 6.2.6 by Jan Wielemaker, University of Amsterdam}}
<langsyntaxhighlight lang="prolog">% 8 queens problem.
% q(Row) represents a queen, allocated one per row. No rows ever clash.
% The columns are chosen iteratively from available columns held in a
Line 11,782 ⟶ 12,358:
length(Boards, Len), writef('%w solutions:\n', [Len]), % Output solutions
member(R,Boards), reverse(R,Board), writef(' - %w\n', [Board]), fail.
queens.</langsyntaxhighlight>
{{out}}
<pre>?- queens.
Line 11,799 ⟶ 12,375:
===Short version===
SWI-Prolog 7.2.3
<langsyntaxhighlight Prologlang="prolog">not_diagonal(X, N) :-
maplist(plus, X, N, Z1), maplist(plus, X, Z2, N), is_set(Z1), is_set(Z2).
 
queens(N, Qs) :-
numlist(1, N, P), findall(Q, (permutation(P, Q), not_diagonal(Q, P)), Qs).</langsyntaxhighlight>
{{out}}
<pre>
Line 11,812 ⟶ 12,388:
 
===SWISH Prolog version===
<syntaxhighlight lang="prolog">
<lang Prolog>
% John Devou: 26-Nov-2021
% Short solution to use on https://swish.swi-prolog.org/.
Line 11,823 ⟶ 12,399:
not((member((U,V),Qs), (V =:= C; R-U =:= abs(C-V)))).
q(N,X):- q(N,N,_,X).
</syntaxhighlight>
</lang>
 
===CLP(FD): Constraint Logic Programming over Finite Domains Version===
Line 11,846 ⟶ 12,422:
</ul>
<br/>
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
 
% DOC: http://www.pathwayslms.com/swipltuts/clpfd/clpfd.html
Line 11,918 ⟶ 12,494:
main :-
print_nqueens_all(8).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 11,946 ⟶ 12,522:
From the Pure (programming language) Wikipedia page
 
<langsyntaxhighlight lang="pure">/*
n-queens.pure
Tectonics:
Line 11,964 ⟶ 12,540:
 
compiling || (puts("queens 4: " + str(queens 4)) $$
puts("Solutions to queens 7: " + str(#queens 7)));</langsyntaxhighlight>
 
{{out}}
Line 11,982 ⟶ 12,558:
=={{header|PureBasic}}==
A recursive approach is taken. A queen is placed in an unused column for each new row. An array keeps track if a queen has already been placed in a given column so that no duplicate columns result. That handles the Rook attacks. Bishop attacks are handled by checking the diagonal alignments of each new placement against the previously placed queens and if an attack is possible the solution backtracks. The solutions are kept track of in a global variable and the routine <tt>queens(n)</tt> is called with the required number of queens specified.
<langsyntaxhighlight PureBasiclang="purebasic">Global solutions
 
Procedure showBoard(Array queenCol(1))
Line 12,061 ⟶ 12,637:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output showing the last solution (all are actually displayed) for 1 - 12 queens:
<pre style="height:40ex;overflow:scroll"> Solution 1
Line 12,184 ⟶ 12,760:
This solution, originally by [http://code.activestate.com/recipes/576647/ Raymond Hettinger] for demonstrating the power of the itertools module, generates all solutions. On a regular 8x8 board only 40,320 possible queen positions are examined.
 
<langsyntaxhighlight lang="python">from itertools import permutations
 
n = 8
Line 12,191 ⟶ 12,767:
if n == len(set(vec[i]+i for i in cols)) \
== len(set(vec[i]-i for i in cols)):
print ( vec )</langsyntaxhighlight>
 
The output is presented in vector form (each number represents the column position of a queen on consecutive rows).
The vector can be pretty printed by substituting a call to <code>board</code> instead of <code>print</code>, with the same argument, and where board is pre-defined as:
<langsyntaxhighlight lang="python">def board(vec):
print ("\n".join('.' * i + 'Q' + '.' * (n-i-1) for i in vec) + "\n===\n")</langsyntaxhighlight>
 
Raymond's description is:
Line 12,211 ⟶ 12,787:
On a regular 8x8 board only 15,720 possible queen positions are examined.
{{works with|Python|2.6, 3.x}}
<langsyntaxhighlight lang="python"># From: http://wiki.python.org/moin/SimplePrograms, with permission from the author, Steve Howell
BOARD_SIZE = 8
 
Line 12,227 ⟶ 12,803:
return solutions
 
for answer in solve(BOARD_SIZE): print(list(enumerate(answer, start=1)))</langsyntaxhighlight>
 
===Python: Simple Backtracking Solution===
Line 12,233 ⟶ 12,809:
to a generator expression) produces a backtracking solution. On a regular 8x8 board only 15,720 possible queen positions are examined.
{{works with|Python|2.6, 3.x}}
<langsyntaxhighlight lang="python">BOARD_SIZE = 8
 
def under_attack(col, queens):
Line 12,251 ⟶ 12,827:
answers = solve(BOARD_SIZE)
first_answer = next(answers)
print(list(enumerate(first_answer, start=1)))</langsyntaxhighlight>
 
===Python: Simple Backtracking Solution (Niklaus Wirth Algorithm)algorithm===
The following program is a translation of Niklaus Wirth's solution into the Python programming language, but does without the index arithmetic used in the original and uses simple lists instead, which means that the array ''x'' for recording the solution can be omitted. A generator replaces the procedure (see [https://www.inf.ethz.ch/personal/wirth/AD Niklaus Wirth] or [https://informatika-21.pdfru/ADen/ Fyodor Tkachov]: Algorithms and Data Structures], pages 114 to 118). On a regular 8x8 board only 15,720 possible queen positions are examined.
<langsyntaxhighlight lang="python">def queens(n: int, i: int, a: list, b: list, c: list):
if i < n:
for j in range(n):
Line 12,262 ⟶ 12,838:
else:
yield a
 
 
for solution in queens(8, 0, [], [], []):
print(solution)</langsyntaxhighlight>
The algorithm can be slightlyeasily improved by using permutations and O(1) sets instead of lists O(cf. backtracking on permutationsn). Butlists thisand makesby theavoiding algorithmunnecessary acopy bitoperations harderduring torecursion. read,An since theadditional list ''x'' has to bewas added to record the solution. On a regular 8x8 board only 5,508 possible queen positions are examined. However, since these two solutions are intended for educational purposes, they are neither resource-friendly nor optimized for speed. The next program (backtracking on permutations) shows a much faster solution that also uses less space on the stack.
<syntaxhighlight lang ="python">def queens(x,i: iint, a, b,: cset):
if a: # set a is not empty
for j in a:
if i + j not in b and i - j not in c:
yield from queensb.add(xi + [j],); c.add(i + 1, a - {j}, b | {i + j}, c | {i -); x.append(j})
yield from queens(i + 1, a - {j})
b.remove(i + j); c.remove(i - j); x.pop()
else:
yield x
 
for solution in queens([], 0, set(range(8)), set(), set()):
print(solution)</lang>
 
b = set(); c = set(); x = []
===Python: backtracking on permutations===
for solution in queens(0, set(range(8))):
print(solution)</syntaxhighlight>
 
===Python: Backtracking on permutations===
Queens positions on a n x n board are encoded as permutations of [0, 1, ..., n]. The algorithms consists in building a permutation from left to right, by swapping elements of the initial [0, 1, ..., n], recursively calling itself unless the current position is not possible. The test is done by checking only diagonals, since rows/columns have by definition of a permutation, only one queen.
 
This is initially a translation of the Fortran 77 solution. The solutions are returned as a generator, using the "yield from" functionality of Python 3.3, described in [https://www.python.org/dev/peps/pep-0380/ PEP-380]. On a regular 8x8 board only 5,508 possible queen positions are examined.
 
<syntaxhighlight lang="python">def queens(n: int):
The solutions are returned as a generator, using the "yield from" functionality of Python 3.3, described in [https://www.python.org/dev/peps/pep-0380/ PEP-380].
 
<lang python> def queenssub(ni: int):
a = list(range( if i < n)):
up = [True]*(2*n - 1)
down = [True]*(2*n - 1)
def sub(i):
if i == n:
yield tuple(a)
else:
for k in range(i, n):
j = a[k]
p =if b[i + j] and c[i - j]:
q = i - j + n - 1
if up[p] and down[q]:
up[p] = down[q] = False
a[i], a[k] = a[k], a[i]
b[i + j] = c[i - j] = False
yield from sub(i + 1)
upb[pi + j] = downc[qi - j] = True
a[i], a[k] = a[k], a[i]
else:
yield a
 
a = list(range(n))
b = [True] * (2 * n - 1)
c = [True] * (2 * n - 1)
yield from sub(0)
 
#Count solutions for n=8:
sum(1 for p in queens(8))
92</lang>
 
sum(1 for p in queens(8)) # count solutions
The preceding function does not enumerate solutions in lexicographic order, see [[Permutations#Recursive implementation]] for an explanation. The following does, but is almost 50% slower, because the exchange is always made (otherwise the loop to shift the array a by one place would not work). On a regular 8x8 board only 5,508 possible queen positions are examined.
92</syntaxhighlight>
 
The preceding function does not enumerate solutions in lexicographic order, see [[Permutations#Recursive implementation]] for an explanation. The following does, but is almost 50% slower, because the exchange is always made (otherwise, restoring the state of the array after the loop wouldn't work). On a regular 8x8 board only 5,508 possible queen positions are examined.
 
However, it may be interesting to look at the first solution in lexicographic order: for growing n, and apart from a +1 offset, it gets closer and closer to the sequence [http://oeis.org/A065188 A065188] at OEIS. The first n for which the first solutions differ is n=26.
 
<langsyntaxhighlight lang="python">def queens_lex(n: int):
 
a = list(range(n))
updef = [True]*sub(2*n -i: 1int):
down = [True]*(2*n - 1)if i < n:
def sub(i):
if i == n:
yield tuple(a)
else:
for k in range(i, n):
j = a[k]
a[i], a[k] = a[k], a[i]
if b[i + j] =and ac[i - j]:
p = b[i + j] = c[i - j] = False
q = i - j + n - 1
if up[p] and down[q]:
up[p] = down[q] = False
yield from sub(i + 1)
upb[pi + j] = downc[qi - j] = True
xa[i:(n - 1)], a[n - 1] = a[(i + 1):n], a[i]
for k in range(i + 1, n)else:
a[k - 1] =yield a[k]
 
a[n - 1] = x
a = list(range(n))
b = [True] * (2 * n - 1)
c = [True] * (2 * n - 1)
yield from sub(0)
 
 
next(queens(31))
([0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20)]
 
next(queens_lex(31))
([0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20)]
 
#Compare to A065188
#1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ...</langsyntaxhighlight>
 
===Python: fold/reduce===
Expressed in terms of nested folds, allowing for graphic display of results, and listing the number of solutions found for boards of various sizes. On a regular 8x8 board only 15,720 possible queen positions are examined.
{{Works with|Python|3.7}}
<langsyntaxhighlight Pythonlang="python">'''N Queens problem'''
 
from functools import reduce
Line 12,492 ⟶ 13,069:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>10 solutions for a 5 * 5 board:
Line 12,514 ⟶ 13,091:
9 -> 352
10 -> 724</pre>
 
=={{header|Quackery}}==
 
<code>perms</code> is defined at [[Permutations#Quackery]]. The solution used determines the order in which the n-Queen solutions found are listed. The output illustrated here is from the <code>perms</code> solution titled "An Uncommon Ordering".
 
The method used here stems from the following observations.
 
* Queens can attach with rook (castle) moves or bishop moves.
 
* The solutions to the N-rooks problem correspond to the permutations of the numbers 0 to N-1 in a zero-indexed list.
 
* Two queens are attacking one another with bishop moves to the left (from the appropriate point of view) if the sum of the x-coordinate and the y-coordinate for each of the queens is the same.
 
* A bishop move to the right is the mirror image of a bishop move to the left.
 
<syntaxhighlight lang="Quackery"> [ false 0 rot
witheach
[ i + bit
2dup & iff
[ drop dip not
conclude ]
done
| ]
drop ] is l-bishop ( [ --> b )
 
[ reverse l-bishop ] is r-bishop ( [ --> b )
 
[ [] swap perms
witheach
[ dup l-bishop iff
drop done
dup r-bishop iff
drop done
nested join ] ] is queens ( n --> [ )
 
8 queens
dup size echo say " solutions."
cr cr
witheach
[ echo
i^ 1+ 4 mod iff sp else cr ]</syntaxhighlight>
 
{{out}}
 
<pre>92 solutions.
 
[ 4 1 5 0 6 3 7 2 ] [ 5 2 4 6 0 3 1 7 ] [ 5 3 6 0 2 4 1 7 ] [ 2 5 1 6 4 0 7 3 ]
[ 5 2 0 6 4 7 1 3 ] [ 5 1 6 0 2 4 7 3 ] [ 5 3 6 0 7 1 4 2 ] [ 2 5 1 6 0 3 7 4 ]
[ 5 2 6 1 3 7 0 4 ] [ 5 2 6 3 0 7 1 4 ] [ 1 5 0 6 3 7 2 4 ] [ 5 1 6 0 3 7 4 2 ]
[ 5 2 6 1 7 4 0 3 ] [ 4 6 1 5 2 0 3 7 ] [ 4 6 1 5 2 0 7 3 ] [ 3 6 4 2 0 5 7 1 ]
[ 3 6 4 1 5 0 2 7 ] [ 6 4 2 0 5 7 1 3 ] [ 3 1 6 2 5 7 0 4 ] [ 3 1 6 2 5 7 4 0 ]
[ 0 6 3 5 7 1 4 2 ] [ 6 1 5 2 0 3 7 4 ] [ 1 6 2 5 7 4 0 3 ] [ 6 2 0 5 7 4 1 3 ]
[ 4 1 3 6 2 7 5 0 ] [ 2 4 6 0 3 1 7 5 ] [ 4 6 3 0 2 7 5 1 ] [ 4 6 1 3 7 0 2 5 ]
[ 1 4 6 3 0 7 5 2 ] [ 4 6 0 3 1 7 5 2 ] [ 4 2 0 6 1 7 5 3 ] [ 1 4 6 0 2 7 5 3 ]
[ 4 6 0 2 7 5 3 1 ] [ 3 1 6 4 0 7 5 2 ] [ 6 3 1 4 7 0 2 5 ] [ 2 0 6 4 7 1 3 5 ]
[ 1 6 4 7 0 3 5 2 ] [ 0 6 4 7 1 3 5 2 ] [ 3 6 2 7 1 4 0 5 ] [ 3 6 0 7 4 1 5 2 ]
[ 6 1 3 0 7 4 2 5 ] [ 2 6 1 7 4 0 3 5 ] [ 6 2 7 1 4 0 5 3 ] [ 6 3 1 7 5 0 2 4 ]
[ 2 6 1 7 5 3 0 4 ] [ 6 0 2 7 5 3 1 4 ] [ 4 1 3 5 7 2 0 6 ] [ 4 0 3 5 7 1 6 2 ]
[ 4 2 0 5 7 1 3 6 ] [ 3 5 0 4 1 7 2 6 ] [ 5 3 0 4 7 1 6 2 ] [ 5 2 4 7 0 3 1 6 ]
[ 2 5 1 4 7 0 6 3 ] [ 5 0 4 1 7 2 6 3 ] [ 2 5 3 1 7 4 6 0 ] [ 2 5 3 0 7 4 6 1 ]
[ 5 3 1 7 4 6 0 2 ] [ 5 2 0 7 4 1 3 6 ] [ 2 5 7 0 4 6 1 3 ] [ 1 3 5 7 2 0 6 4 ]
[ 3 5 7 2 0 6 4 1 ] [ 3 5 7 1 6 0 2 4 ] [ 2 5 7 1 3 0 6 4 ] [ 2 5 7 0 3 6 4 1 ]
[ 5 2 0 7 3 1 6 4 ] [ 1 5 7 2 0 3 6 4 ] [ 5 7 1 3 0 6 4 2 ] [ 0 5 7 2 6 3 1 4 ]
[ 3 1 4 7 5 0 2 6 ] [ 3 0 4 7 5 2 6 1 ] [ 4 7 3 0 2 5 1 6 ] [ 2 4 1 7 5 3 6 0 ]
[ 0 4 7 5 2 6 1 3 ] [ 4 0 7 5 2 6 1 3 ] [ 3 1 7 5 0 2 4 6 ] [ 7 2 0 5 1 4 6 3 ]
[ 1 7 5 0 2 4 6 3 ] [ 3 7 0 2 5 1 6 4 ] [ 7 3 0 2 5 1 6 4 ] [ 3 0 4 7 1 6 2 5 ]
[ 2 4 7 3 0 6 1 5 ] [ 4 2 7 3 6 0 5 1 ] [ 4 1 7 0 3 6 2 5 ] [ 4 0 7 3 1 6 2 5 ]
[ 4 7 3 0 6 1 5 2 ] [ 2 4 1 7 0 6 3 5 ] [ 3 7 4 2 0 6 1 5 ] [ 3 1 7 4 6 0 2 5 ]
[ 3 7 0 4 6 1 5 2 ] [ 7 1 4 2 0 6 3 5 ] [ 7 1 3 0 6 4 2 5 ] [ 2 7 3 6 0 5 1 4 ]</pre>
 
=={{header|QBasic}}==
{{works with|QBasic}}
{{trans|QB64}}
<langsyntaxhighlight QBasiclang="qbasic">DIM SHARED queens AS INTEGER
CLS
COLOR 15
Line 12,562 ⟶ 13,208:
continue1:
NEXT icol
END SUB</langsyntaxhighlight>
 
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>
DIM SHARED QUEENS AS INTEGER
PRINT "# of queens:";: INPUT QUEENS
Line 12,606 ⟶ 13,252:
NEXT icol
END SUB
</syntaxhighlight>
</lang>
 
=={{header|R}}==
Line 12,614 ⟶ 13,260:
This solution uses recursive backtracking.
 
<langsyntaxhighlight lang="r">queens <- function(n) {
a <- seq(n)
u <- rep(T, 2 * n - 1)
Line 12,641 ⟶ 13,287:
aux(1)
m
}</langsyntaxhighlight>
 
Show the first solution found for size 8 as a permutation matrix.
 
<langsyntaxhighlight Rlang="r">library(Matrix)
a <- queens(8)
as(a[, 1], "pMatrix")</langsyntaxhighlight>
 
{{out}}
Line 12,664 ⟶ 13,310:
Count solutions for board size 4 to 12.
 
<langsyntaxhighlight Rlang="r">sapply(4:12, function(n) ncol(queens(n)))</langsyntaxhighlight>
 
{{out}}
Line 12,674 ⟶ 13,320:
Backtracking algorithm; returns one solution
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 12,705 ⟶ 13,351:
(nqueens 8)
; => (list (Q 3 7) (Q 1 6) (Q 6 5) (Q 2 4) (Q 5 3) (Q 7 2) (Q 4 1) (Q 0 0))
</syntaxhighlight>
</lang>
 
Show result with "How to Design Programs" GUI.
<langsyntaxhighlight lang="racket">
(require htdp/show-queen)
 
Line 12,719 ⟶ 13,365:
 
(show-nqueens 8)
</syntaxhighlight>
</lang>
 
[[image:Racket-nqueens.png]]
Line 12,731 ⟶ 13,377:
Computes all solutions.
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 12,777 ⟶ 13,423:
'() qss-so-far)))
(lazy-filter valid? all-possible-solutions))
</syntaxhighlight>
</lang>
 
Taking the first solution does not compute the other solutions:
 
<langsyntaxhighlight lang="racket">
(car (nqueens 8))
;; => (list (Q 7 3) (Q 6 1) (Q 5 6) (Q 4 2) (Q 3 5) (Q 2 7) (Q 1 4) (Q 0 0))
</syntaxhighlight>
</lang>
 
Computing all solutions is also possible:
 
<langsyntaxhighlight lang="racket">
(define (force-and-print qs)
(define forced (force qs))
Line 12,806 ⟶ 13,452:
;(list (Q 7 3) (Q 6 6) (Q 5 4) (Q 4 1) (Q 3 5) (Q 2 0) (Q 1 2) (Q 0 7))
;(list (Q 7 4) (Q 6 6) (Q 5 1) (Q 4 5) (Q 3 2) (Q 2 0) (Q 1 3) (Q 0 7))
</syntaxhighlight>
</lang>
 
Logic borrowed from the Ruby example
<langsyntaxhighlight lang="racket">
#lang racket
(define (remove x lst)
Line 12,866 ⟶ 13,512:
(define (print-queens n)
(for ([x (queens n)]) (displayln (string-join x))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 12,873 ⟶ 13,519:
Neither pretty nor efficient, a simple backtracking solution
 
<syntaxhighlight lang="raku" perl6line>sub MAIN(\N = 8) {
sub collision(@field, $row) {
for ^$row -> $i {
Line 12,896 ⟶ 13,542:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[0 4 7 5 2 6 1 3]</pre>
Line 12,902 ⟶ 13,548:
=={{header|Rascal}}==
 
<langsyntaxhighlight Rascallang="rascal">import Prelude;
 
public set[list[int]] Nqueens(int n){
Line 12,911 ⟶ 13,557:
result += vector;}
return result;
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 12,920 ⟶ 13,566:
 
About half of the REXX code involves presentation (and colorization achieved through dithering) of the chessboard and queens.
<langsyntaxhighlight lang="rexx">/*REXX program places N queens on an NxN chessboard (the eight queens problem). */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 8 /*Not specified: Then use the default.*/
Line 12,969 ⟶ 13,615:
say pad _ || bar /*show a single rank of the board.*/
end /*rank*/ /*80 cols can view a 19x19 board.*/
say pad translate('╚'g"╝", '╩', "╬"); return /*display the last rank (of board)*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default of an &nbsp; '''8'''<small>x</small>'''8''' &nbsp; chessboard:}}
<pre>
Line 13,040 ⟶ 13,686:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
 
// Bert Mariani 2020-07-17
Line 13,089 ⟶ 13,735:
//================================
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 13,112 ⟶ 13,758:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
load "guilib.ring"
Line 13,801 ⟶ 14,447:
 
###============================================================
</syntaxhighlight>
</lang>
[https://www.mediafire.com/file/53bxu7kpuc4tlx5/Images.zip/file Necessary images]
 
=={{header|Ruby}}==
This implements the heuristics found on the wikipedia page to return just one solution
<langsyntaxhighlight lang="ruby"># 1. Divide n by 12. Remember the remainder (n is 8 for the eight queens
# puzzle).
# 2. Write a list of the even numbers from 2 to n in order.
Line 13,862 ⟶ 14,508:
end
(1 .. 15).each {|n| puts "n=#{n}"; puts n_queens(n); puts}</langsyntaxhighlight>
 
{{out}}
Line 14,016 ⟶ 14,662:
===Alternate solution===
If there is not specification, it outputs all solutions.
<langsyntaxhighlight lang="ruby">class Queen
attr_reader :count
Line 14,054 ⟶ 14,700:
puts @frame
end
end</langsyntaxhighlight>
 
'''Example:'''
<langsyntaxhighlight lang="ruby">(1..6).each do |n|
puzzle = Queen.new(n)
puts " #{n} Queen : #{puzzle.count}"
Line 14,065 ⟶ 14,711:
puzzle = Queen.new(n, false) # do not display
puts " #{n} Queen : #{puzzle.count}"
end</langsyntaxhighlight>
 
{{out}}
Line 14,201 ⟶ 14,847:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">[loop]
input "How many queens (N>=4)";n
if n < 4 then
Line 14,312 ⟶ 14,958:
end if
end if
next</langsyntaxhighlight>
<pre>abcdefgh
* 8
Line 14,324 ⟶ 14,970:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">const N: usize = 8;
 
fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) {
Line 14,356 ⟶ 15,002:
try (&mut board, 0, &mut count);
println!("Found {} solutions", count)
}</langsyntaxhighlight>
 
===Using Iterators===
Solution to the puzzle using an iterator that yields the 92 solutions for 8 queens.
 
<lang rust>use std::collections::LinkedList;
<syntaxhighlight lang="rust">
use std::collections::LinkedList;
use std::iter::IntoIterator;
 
Line 14,369 ⟶ 15,017:
}
 
fn permutations<'a, T, I>(collection: I) -> Box<Iterator<dyn Item=LinkedList<T>> + 'a>
where I: 'a + IntoIterator<Item=T> + Clone,
T: 'a + PartialEq + Copy + Clone {
Line 14,388 ⟶ 15,036:
 
pub struct NQueens {
iterator: Box<Iterator<dyn Item=NQueensSolution>>
}
 
Line 14,436 ⟶ 15,084:
str
}
}
}</lang>
</syntaxhighlight>
 
===Permutation with Filtering===
 
Using Itertools and arrays.
 
{{trans|D}}
 
<syntaxhighlight lang="rust">
extern crate itertools;
 
use itertools::Itertools;
 
fn main() {
const N: usize = 8;
 
let permutations = (0..N).permutations(N);
let solution_count = permutations
.filter(|p| {
let mut diag1 = [false; 2 * N - 1];
let mut diag2 = [false; 2 * N - 1];
for (i, &row) in p.iter().enumerate() {
if diag1[row + i] || diag2[N - 1 + row - i] {
return false; // Queens mutual threat
}
diag1[row + i] = true;
diag2[N - 1 + row - i] = true;
}
true // No Queens mutual threat
})
.count();
 
println!("{}", solution_count);
}
</syntaxhighlight>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">/* Store all 92 permutations in a SAS dataset. Translation of Fortran 77 */
data queens;
array a{8} p1-p8;
Line 14,496 ⟶ 15,183:
put n m;
keep p1-p8;
run;</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 14,504 ⟶ 15,191:
Lazily generates permutations with an <code>Iterator</code>.
 
<langsyntaxhighlight lang="scala">
object NQueens {
 
Line 14,554 ⟶ 15,241:
}
}
</syntaxhighlight>
</lang>
 
<pre>
Line 14,585 ⟶ 15,272:
This is a simple breadth-first technique to retrieve all solutions.
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 14,660 ⟶ 15,347:
(pretty-print (n-queens 5) 5)
(pretty-print (n-queens 8) 8)
</syntaxhighlight>
</lang>
 
{{out}}
Line 14,734 ⟶ 15,421:
=={{header|Scilab}}==
Naive brute-force search.
<syntaxhighlight lang="scilab">//Length of board side
Board_size = 8;
 
Line 14,875 ⟶ 15,562:
string(Board_size)+"x"+string(Board_size)+" board.");
//Time elapsed
disp("Time: "+string(toc())+"s.");</langsyntaxhighlight>
 
{{out}}
Line 14,884 ⟶ 15,571:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
var array integer: board is 8 times 0;
Line 14,934 ⟶ 15,621:
end if;
end while;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func N_queens_solution(N = 8) {
 
func collision(field, row) {
Line 14,968 ⟶ 15,655:
for n in (1..15) {
say "#{'%2d' % n}: #{N_queens_solution(n) || 'No solution'}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 14,989 ⟶ 15,676:
 
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
<lang SNOBOL4>
* N queens problem
* Set N to the desired number. The program prints out all solution boards.
Line 15,013 ⟶ 15,700:
PRTLOOP B LEN(NP1) . OUTPUT = :S(PRTLOOP)F(RETURN)
END
</syntaxhighlight>
</lang>
 
=={{header|Sparkling}}==
This is somewhat a transliteration of the "shortened" C++ code above.
 
<langsyntaxhighlight lang="sparkling">let print_table = function (pos) {
pos.foreach(function (_, i) {
stdout.printf(" %c", 'a' + i);
Line 15,071 ⟶ 15,758:
};
 
stdout.printf("%d solutions\n", n_queens(range(8), 0));</langsyntaxhighlight>
 
=={{header|SQL}}==
Line 15,077 ⟶ 15,764:
This implementation, which solves the problem for n=8, makes use of Common Table Expressions and has been tested with SQLite (>=3.8.3) and Postgres (please note the related comment in the code). It might be compatible with other SQL dialects as well. A gist with the SQL file and a Python script that runs it using SQLite is available on Github: https://gist.github.com/adewes/5e5397b693eb50e67f07
 
<syntaxhighlight lang="sql">
<lang SQL>
WITH RECURSIVE
positions(i) as (
Line 15,108 ⟶ 15,795:
SELECT board,n_queens FROM solutions WHERE n_queens = 8;
 
</syntaxhighlight>
</lang>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<langsyntaxhighlight lang="sql pl">
-- A column of a matrix.
CREATE TYPE INTEGER_ARRAY AS INTEGER ARRAY[]@
Line 15,392 ⟶ 16,079:
 
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 15,431 ⟶ 16,118:
=={{header|Standard ML}}==
This implementation uses failure continuations for backtracking.
<syntaxhighlight lang="standard ml">
<lang Standard ML>
(*
* val threat : (int * int) -> (int * int) -> bool
Line 15,471 ⟶ 16,158:
(* NONE *)
queens(2);
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
Line 15,477 ⟶ 16,164:
Adapted from the Fortran 77 program, to illustrate the '''[http://www.stata.com/help.cgi?m2_goto goto]''' statement in Stata.
 
<langsyntaxhighlight lang="stata">mata
real matrix queens(real scalar n) {
real scalar i, j, k, p, q
Line 15,534 ⟶ 16,221:
rows(a)
92
end</langsyntaxhighlight>
 
It's also possible to save the solutions to a Stata dataset:
 
<langsyntaxhighlight lang="stata">clear
mata: a=queens(8)
getmata (a*)=a
save queens, replace</langsyntaxhighlight>
 
=== Recursive version ===
Line 15,547 ⟶ 16,234:
The recursive solution is adapted from one of the Python programs.
 
<langsyntaxhighlight lang="stata">mata
real matrix queens_rec(real scalar n) {
real rowvector a, u, v
Line 15,583 ⟶ 16,270:
}
}
end</langsyntaxhighlight>
 
The iterative and the recursive programs are equivalent:
 
<langsyntaxhighlight lang="stata">queens(8) == queens_rec(8)
1</langsyntaxhighlight>
 
=={{header|Swift}}==
Port of the optimized C code above
<syntaxhighlight lang="swift">
<lang Swift>
let maxn = 31
 
Line 15,650 ⟶ 16,337:
}
 
</syntaxhighlight>
</lang>
 
=={{header|SystemVerilog}}==
Create a random board configuration, with the 8-queens as a constraint
<langsyntaxhighlight SystemVeriloglang="systemverilog">program N_queens;
 
parameter SIZE_LOG2 = 3;
Line 15,691 ⟶ 16,378:
 
endprogram
</syntaxhighlight>
</lang>
 
=={{header|Tailspin}}==
A functional-ish solution utilising tailspin's data flows
<langsyntaxhighlight lang="tailspin">
templates queens
def n: $;
Line 15,727 ⟶ 16,414:
'For 3 queens there are $:[3 -> queens] -> $::length; solutions
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 15,736 ⟶ 16,423:
 
A solution using state to find one solution if any exist
<langsyntaxhighlight lang="tailspin">
templates queens
def n: $;
templates getRowColumn
when <?($@queens.freeRows($.r::raw) <=0>)> do 0 !
when <?($@queens.freeMaxs($.r::raw + $.c::raw) <=0>)> do 0 !
when <?($@queens.freeMins($.c::raw - $.r::raw + $n) <=0>)> do 0 !
Line 15,748 ⟶ 16,435:
sink setRowColumn
def p: $;
@queens.freeRows($p.r::raw): $p.val::raw;
@queens.freeMaxs($p.c::raw + $p.r::raw): $p.val::raw;
@queens.freeMins($p.c::raw - $p.r::raw + $n): $p.val::raw;
Line 15,762 ⟶ 16,449:
when <?({r: $, c: $c} -> getRowColumn <=1>)> do
def r: $;
@queens.queenRows($r::raw): $c;
{r: $, c: $c, val: 0} -> !setRowColumn
$c -> \(<=col´$n> done´1!
Line 15,785 ⟶ 16,472:
'A solution to the 3 queens problem is $:3 -> queens;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 15,797 ⟶ 16,484:
 
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc unsafe {y} {
Line 15,843 ⟶ 16,530:
}
 
main [expr {$argc ? int(0+[lindex $argv 0]) : 8}]</langsyntaxhighlight>
{{out}}
<pre>$ tclsh8.5 8queens.tcl 6
Line 15,886 ⟶ 16,573:
The total number of solutions for 8 queens is displayed at the end of the run. The code could be adapted to display a selected solution or multiple solutions. This code runs anywhere you can get bash to run.
 
<langsyntaxhighlight lang="bash">#!/bin/bash
# variable declaration
Line 15,963 ⟶ 16,650:
work
out
depose</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 15,969 ⟶ 16,656:
n is a number greater than 3. Multiple solutions may be reported
but reflections and rotations thereof are omitted.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 15,986 ⟶ 16,673:
-<&l^|*DlrTS/~& ~&iiDlSzyCK9hlPNNXXtCS,
^jrX/~& @rZK20lrpblPOlrEkPK13lhPK2 ~&i&& nleq$-&lh+-,
^/~&NNXS+iota -<&l+ ~&plll2llr2lrPrNCCCCNXS*=irSxPSp+ ^H/block iota; *iiK0 ^/~& sum+-</langsyntaxhighlight>
The output shows one solution on each line.
A solution is reported as a sequence of <math>n</math> numbers
Line 16,004 ⟶ 16,691:
=={{header|VBA}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="vb">'N-queens problem - non recursive & structured - vba - 26/02/2017
Sub n_queens()
Const l = 15 'number of queens
Line 16,061 ⟶ 16,748:
Debug.Print n, m 'number of queens, number of solutions
Next n
End Sub 'n_queens</langsyntaxhighlight>
{{out}}
<pre>
Line 16,084 ⟶ 16,771:
{{trans|BBC BASIC}}
To have the solutions printed (raw format) uncomment the ad hoc statement.
<langsyntaxhighlight lang="vb">'N-queens problem - non recursive & structured - vbs - 24/02/2017
const l=15
dim a(),s(),u(): redim a(l),s(l),u(4*l-2)
Line 16,129 ⟶ 16,816:
Loop Until i=0
wscript.echo n &":"& m
next 'n</langsyntaxhighlight>
{{out}}
<pre>
Line 16,152 ⟶ 16,839:
{{works with|Visual Basic|VB6 Standard}}
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="vb">'N-queens problem - non recursive & structured - vb6 - 25/02/2017
Sub n_queens()
Const l = 15 'number of queens
Line 16,209 ⟶ 16,896:
Debug.Print n, m 'number of queens, number of solutions
Next n
End Sub 'n_queens</langsyntaxhighlight>
{{out}}
<pre>
Line 16,231 ⟶ 16,918:
=={{header|Visual Basic .NET}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="vb">'N-queens problem - non recursive & structured - vb.net - 26/02/2017
Module Mod_n_queens
Sub n_queens()
Line 16,291 ⟶ 16,978:
Next n
End Sub 'n_queens
End Module</langsyntaxhighlight>
{{out}}
<pre>
Line 16,312 ⟶ 16,999:
 
=={{header|Wart}}==
<langsyntaxhighlight Wartlang="wart">def (nqueens n queens)
prn "step: " queens # show progress
if (len.queens = n)
Line 16,335 ⟶ 17,022:
def (diagonal_match curr other)
(= (abs (curr.0 - other.0))
(abs (curr.1 - other.1)))</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
Very slow for the larger boards.
<langsyntaxhighlight ecmascriptlang="wren">var count = 0
var c = []
var f = []
Line 16,377 ⟶ 17,064:
if (count > 0) System.print(" First is %(f)")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 16,439 ⟶ 17,126:
 
Copied from http://www.cs.bu.edu/~hwxi/Xanadu/Examples/
<syntaxhighlight lang="xanadu">
<lang Xanadu>
int abs(i: int) {
if (i >= 0) return i; else return -i;
Line 16,508 ⟶ 17,195:
int main () {
return queen (8);
}</langsyntaxhighlight>
 
=={{header|XPL0}}==
[[File:NQueensXPL0.GIF|right]]
<langsyntaxhighlight XPL0lang="xpl0">def N=8; \board size (NxN)
int R, C; \row and column of board
char B(N,N); \board
Line 16,568 ⟶ 17,255:
C:= 0; \start at left column
Try;
]</langsyntaxhighlight>
 
=={{header|XSLT}}==
Line 16,574 ⟶ 17,261:
(either by XSLT processors saxon-6.5.5, xsltproc, xalan,
or any of the big5 browsers):
<langpre>
15863724
16837425
Line 16,580 ⟶ 17,267:
83162574
84136275
</langpre>
 
You can view the results directly in your browser (Chrome/FF/IE/Opera/Safari) here: [[http://stamm-wilbrandt.de/en/xsl-list/n-queens/8-queens.xsl.xml]]
Line 16,599 ⟶ 17,286:
 
Here is stylesheet 8-queens.xsl.xml which produces the (simple) output by having itself as input: [[http://stamm-wilbrandt.de/en/xsl-list/n-queens/8-queens.xsl.xml]]
<langsyntaxhighlight lang="xml">
<!-- 8-queens.xsl disguised as XML file for the browsers -->
 
Line 16,726 ⟶ 17,413:
 
</xsl:stylesheet>
</syntaxhighlight>
</lang>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">DOCU The N Queens Problem:
DOCU Place N Queens on an NxN chess board
DOCU such that they don't threaten each other.
Line 16,793 ⟶ 17,480:
wend
end sub
</syntaxhighlight>
</lang>
 
=={{header|Zig}}==
Outputs all 92 solutions.
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
Line 16,838 ⟶ 17,525:
}
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 16,851 ⟶ 17,538:
=={{header|zkl}}==
Modified from a Haskell version (if I remember correctly)
<langsyntaxhighlight lang="zkl">fcn isAttacked(q, x,y) // ( (r,c), x,y ) : is queen at r,c attacked by q@(x,y)?
{ r,c:=q; (r==x or c==y or r+c==x+y or r-c==x-y) }
fcn isSafe(r,c,qs) // queen safe at (r,c)?, qs=( (r,c),(r,c)..) solution so far
Line 16,860 ⟶ 17,547:
if (row == N) return(qs);
return(qs.apply(self.fcn.fp(N,row+1)).flatten());
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">queens := queensN(4);
println(queens.len()," solution(s):");
queens.apply2(Console.println);</langsyntaxhighlight>
{{out}}
<pre>
305

edits