Just another update
This commit is contained in:
parent
a25938f123
commit
00a190b0a6
6591 changed files with 94363 additions and 23227 deletions
|
|
@ -2,8 +2,8 @@ safe[q_List, n_] :=
|
|||
With[{l = Length@q},
|
||||
Length@Union@q == Length@Union[q + Range@l] ==
|
||||
Length@Union[q - Range@l] == l]
|
||||
nQueen[q_List:{}, n_] :=
|
||||
nQueen[q_List: {}, n_] :=
|
||||
If[safe[q, n],
|
||||
If[Length[q] == n, q,
|
||||
Cases[Flatten[{nQueen[Append[q, #], n]}, 2] & /@ Range[n],
|
||||
Except[{Null} | {}]]], Null]
|
||||
If[Length[q] == n, {q},
|
||||
Cases[nQueen[Append[q, #], n] & /@ Range[n],
|
||||
Except[{Null} | {}], {2}]], Null]
|
||||
|
|
|
|||
44
Task/N-queens-problem/Mathematica/n-queens-problem-4.math
Normal file
44
Task/N-queens-problem/Mathematica/n-queens-problem-4.math
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
dispSol[sol_] := sol /. {1 -> "Q" , 0 -> "-"} // Grid
|
||||
|
||||
solveNqueens[n_] :=
|
||||
Module[{c, m, b, vars}, c = cqueens[n]; m = mqueens[n];
|
||||
vars = mqueens2[n]; b = bqueens[Length[m]];
|
||||
Partition[LinearProgramming[c, m, b, vars, Integers], n]]
|
||||
|
||||
cqueens[n_] := Table[-1, {i, n^2}]
|
||||
|
||||
bqueens[l_] := Table[{1, -1}, {i, l}]
|
||||
|
||||
mqueens2[n_] := Table[{0, 1}, {i, n^2}]
|
||||
|
||||
mqueens[n_] :=
|
||||
Module[{t, t2, t3, t4}, t = mqueensh[n]; t2 = Append[t, mqueensv[n]];
|
||||
t3 = Append[t2, mqueensd[n]]; t4 = Append[t3, mqueensdm[n]];
|
||||
Partition[Flatten[t4], n^2]]
|
||||
|
||||
mqueensh[n_] :=
|
||||
Module[{t}, t = Table[0, {i, n}, {j, n^2}];
|
||||
For[i = 1, i <= n, i++,
|
||||
For[j = 1, j <= n, j++, t[[i, ((i - 1)*n) + j]] = 1]]; t]
|
||||
|
||||
mqueensv[n_] :=
|
||||
Module[{t}, t = Table[0, {i, n}, {j, n^2}];
|
||||
For[i = 1, i <= n, i++,
|
||||
For[j = 1, j <= n, j++, t[[j, ((i - 1)*n) + j]] = 1]]; t]
|
||||
|
||||
mqueensd[n_] :=
|
||||
Module[{t}, t = Table[0, {i, (2*n) - 1}, {j, n^2}];
|
||||
For[k = 2, k <= 2 n, k++,
|
||||
For[i = 1, i <= n, i++,
|
||||
For[j = 1, j <= n, j++,
|
||||
If[i + j == k, t[[k - 1, ((i - 1)*n) + j]] = 1]]]]; t]
|
||||
|
||||
mqueensdm[n_] :=
|
||||
Module[{t}, t = Table[0, {i, Sum[1, {i, 1 - n, n - 1}]}, {j, n^2}];
|
||||
For[k = 1 - n, k <= n - 1, k++,
|
||||
For[i = 1, i <= n, i++,
|
||||
For[j = 1, j <= n, j++,
|
||||
If[i == j - k, t[[k + n, ((i - 1)*n) + j]] = 1]]]]; t]
|
||||
|
||||
|
||||
solveNqueens[8] // dispSol
|
||||
Loading…
Add table
Add a link
Reference in a new issue