# N皇后问题[关闭]

9

st0le 2011年

Dongshengcn

4

``````(* Define the variables: Q[i,j] indicates whether there is a
Queen in row i, column j *)
Qs = Array[Q, {8, 8}];

(* Define the logical constraints. *)
problem =
And[
(* Each row must have a queen. *)
And @@ Map[(Or @@ #) &, Qs],
(* for all i,j: Q[i,j] implies Not[...] *)
And @@ Flatten[
Qs /. Q[i_, j_] :>
And @@ Map[Implies[Q[i, j], Not[#]] &,
Cases[Qs,
Q[k_, l_] /;
Not[(i == k) && (j == l)] && (
(i == k) ||          (* same row *)
(j == l) ||          (* same column *)
(i + j == k + l) ||  (* same / diagonal *)
(i - j == k - l)),   (* same \ diagonal *)
2]]]];

(* Find the solution *)
solution = FindInstance[problem, Flatten[Qs], Booleans] ;

(* Display the solution *)
Qs /. First[solution] /. {True -> Q, False -> x} // MatrixForm
``````

``````x   x   x   x   Q   x   x   x
x   Q   x   x   x   x   x   x
x   x   x   Q   x   x   x   x
x   x   x   x   x   x   Q   x
x   x   Q   x   x   x   x   x
x   x   x   x   x   x   x   Q
x   x   x   x   x   Q   x   x
Q   x   x   x   x   x   x   x
``````

0

0

### Python 2，190185个字符

```从itertools import *
n =输入（）

```

0

Groovy

``````n=8
s=(1..n).permutations().findAll{
def x=0,y=0
Set a=it.collect{it-x++}
Set b=it.collect{it+y++}
a.size()==it.size()&&b.size()==it.size()
}
``````

``````[ [4, 7, 3, 0, 6, 1, 5, 2],
[6, 2, 7, 1, 4, 0, 5, 3],
... ]
``````

``````s.each { def size = it.size()
it.each { (it-1).times { print "|_" }
print "|Q"
(size-it).times { print "|_" }
println "|"
}
println ""
}
``````

``````|_|Q|_|_|_|_|_|_|
|_|_|_|Q|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|_|_|_|_|_|_|_|Q|
|_|_|Q|_|_|_|_|_|
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|_|Q|_|_|_|
``````