Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. 1) Start in the leftmost column
  2. 2) If all queens are placed return true
  3. 3) Try all rows in the current column. Do following for every tried row.
  4. a) If the queen can be placed safely in this row then mark this [row,
  5. column] as part of the solution and recursively check if placing
  6. queen here leads to a solution.
  7. b) If placing queen in [row, column] leads to a solution then return
  8. true.
  9. c) If placing queen doesn't lead to a solution then umark this [row,
  10. column] (Backtrack) and go to step (a) to try other rows.
  11. 3) If all rows have been tried and nothing worked, return false to trigger
  12. backtracking.
  13.  
  14. grid = SparseArray[{i_, j_} :> 8 (i - 1) + j, {8, 8}] // Normal;
  15. init = ArrayRules@grid; (* saves which position corresponds to which of the 64 values *)
  16.  
  17. checkSafe[grid_, row_, col_] := Module[
  18. {rules = ArrayRules@grid, leftdiag, partialRightDiag1,
  19. partialRightDiag2, currentRow, rightdiag},
  20.  
  21. leftdiag =
  22. Count[rules, PatternSequence[{i_,j_} /; (i + j == row + col) -> [BlackQueen]]];
  23.  
  24. currentRow = Count[grid[[row]], [BlackQueen]];
  25.  
  26. partialRightDiag1 = Rest@NestWhileList[# + 1 &, {row, col}, ! MemberQ[#, 8] &];
  27. partialRightDiag2 = Rest@NestWhileList[# - 1 &, {row, col}, ! MemberQ[#, 1] &];
  28.  
  29. rightdiag = Count[Join[partialRightDiag1, partialRightDiag2] /. rules , [BlackQueen]];
  30. {leftdiag, currentRow, rightdiag}]
  31.  
  32. NQueens[col_] := True /; col > 8;
  33.  
  34. NQueens[col_: 1] := Module[{column = col, temp},
  35. Do[
  36. temp = checkSafe[grid, row, column];
  37. If[Total@temp == 0,
  38. grid[[row, column]] = [BlackQueen];
  39. If[NQueens[column = column + 1] == True, Break[]];
  40. grid[[row, column]] = {row, column} /. init (*remove Queen*)];, {row, 8}]
  41. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement