It is a really succinct but mysterious piece of code. I understand the diff == 0 part, but the diff == rowID - i, I do not understand at all? How did they come up with this?

# How does n-queens isValid check work?

**damluar**#2

the `diff == 0`

condition checks if both queens occupy the same column

the `diff == row - i`

checks if they are on the same diagonal.

Just draw a 4x4 matrix and try to understand when 2 queens are on the same diagonal. There are 2 cases: newly added queen is to the left or to the right of the queen we check against.

1 Like

**triplethreat**#3

It still doesnâ€™t make too much sense, but its ok. I found that an easier way to check the diagonals is to see that for a given diagonal, either i +j = constant or i - j = constant where i and j are the row and column of a given cell in a given diagonal. The absolute value and diff were too hard for me to remember/reason about. THANKS

0 Likes