-2

http://jeffe.cs.illinois.edu/teaching/algorithms/notes/03-backtracking.pdf

enter image description here

explain the highlighted texted of image

Q[i]=j Q[i]=j+r-i Q[i]=j-r+i

how these statements check if two queen attack in row column or diagonals?

Raven
  • 11
  • 4
  • What to explain ? It's checking if: element at index i in Q array is equal to value that's held in j, OR if it's equal to j + r - 1 OR j - r + i, if any of those is true boolean variable legal gets set to false and the code below is not executed because legal is false. – whatamidoingwithmylife Dec 06 '17 at 23:21

1 Answers1

0

That's a better solution than I came up with many years ago when I beat the obvious algorithm by an order of magnitude.

Fundamentally, what this is doing is instead of maintaining a board and checking the three paths that a queen can move (you only need to look behind the queen--it's the only queen on the row so you know that direction is clear an the queens ahead haven't been placed yet) which requires checking (row - 1) * 3 cells (although some are off the board, it may be cheaper to test the diagonals for bounds first) it's maintaining a one dimensional array of queens and noting what they threaten. This reduces each placement test to 3 squares. (And uses only addition, no multiplication. Irrelevant now, a considerable time savings when I was playing with this.)

I haven't looked over the whole thing to see how they are doing it with one array rather than the three I did it with (column threatened, / diagonal threatened, \ diagonal threatened. The latter arrays are twice as big.)

Loren Pechtel
  • 8,945
  • 3
  • 33
  • 45