Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1) Start in the leftmost column
- 2) If all queens are placed return true
- 3) Try all rows in the current column. Do following for every tried row.
- a) If the queen can be placed safely in this row then mark this [row,
- column] as part of the solution and recursively check if placing
- queen here leads to a solution.
- b) If placing queen in [row, column] leads to a solution then return
- true.
- c) If placing queen doesn't lead to a solution then umark this [row,
- column] (Backtrack) and go to step (a) to try other rows.
- 3) If all rows have been tried and nothing worked, return false to trigger
- backtracking.
- grid = SparseArray[{i_, j_} :> 8 (i - 1) + j, {8, 8}] // Normal;
- init = ArrayRules@grid; (* saves which position corresponds to which of the 64 values *)
- checkSafe[grid_, row_, col_] := Module[
- {rules = ArrayRules@grid, leftdiag, partialRightDiag1,
- partialRightDiag2, currentRow, rightdiag},
- leftdiag =
- Count[rules, PatternSequence[{i_,j_} /; (i + j == row + col) -> [BlackQueen]]];
- currentRow = Count[grid[[row]], [BlackQueen]];
- partialRightDiag1 = Rest@NestWhileList[# + 1 &, {row, col}, ! MemberQ[#, 8] &];
- partialRightDiag2 = Rest@NestWhileList[# - 1 &, {row, col}, ! MemberQ[#, 1] &];
- rightdiag = Count[Join[partialRightDiag1, partialRightDiag2] /. rules , [BlackQueen]];
- {leftdiag, currentRow, rightdiag}]
- NQueens[col_] := True /; col > 8;
- NQueens[col_: 1] := Module[{column = col, temp},
- Do[
- temp = checkSafe[grid, row, column];
- If[Total@temp == 0,
- grid[[row, column]] = [BlackQueen];
- If[NQueens[column = column + 1] == True, Break[]];
- grid[[row, column]] = {row, column} /. init (*remove Queen*)];, {row, 8}]
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement