Solution Review: Place N Queens on an NxN Chessboard
In this lesson, we will go over the solution to the challenge from the previous lesson.
We'll cover the following...
Solution #
Explanation
Let’s break down what we did there. The basic idea is to place the queen at all possible positions to find out what fits our needs. We start off placing a queen in the first row’s first box and then make a recursive call to place a queen in the second row. Here we place a queen in a safe position and check recursively again for the next rows. If any of the recursive calls return false, we check the next box on the previous row, and so on.
Look at the visualization of a dry run on an example where n = 4.
Observe how simple and intuitive this solution is. All we are doing is placing queens in a row and checking whether, after placing that queen, we can place queens in proceeding rows. Now if you look at the code, start with line 20, where we iterate over the r ...