We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Safe Positions

Brute force wastes a lot of effort building boards that are obviously doomed. Take this partial layout:

[1, 3]

If we try to place the next queen at row 2, column 1, we don't need to look any further to know it's bad – it shares a column with the queen in row 0:

[1, 3, 1]

Row 2, column 2 is no good either because now it's on the same diagonal as the queen in row 1:

[1, 3, 2]

Partial Boards

Instead of checking a full board after it's complete, we can check each new position before we commit to it:

  • is_valid_board checks whether a finished board is valid.
  • A more targeted function – we'll call it is_safe – checks whether one proposed position is okay given the partial board we've built so far.

If a position is unsafe, we can skip it immediately. There's no reason to keep building on a board layout that's already guaranteed to fail.

Assignment

Complete the is_safe function. It accepts:

  • board: a partial board represented as a list[int]
  • row: the row where we might place the next queen
  • col: the column where we might place the next queen

It should return True if the position is safe, otherwise False. This function should not change the board; it only answers whether appending col for the given row would create a conflict.