...
/Solution Review: Place N Queens on an NxN Chessboard
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 #
Press + to interact
def isSafe(i, j, board):for c in range(len(board)):for r in range(len(board)):# check if i,j share row with any queenif board[c][r] == 'q' and i==c and j!=r:return False# check if i,j share column with any queenelif board[c][r] == 'q' and j==r and i!=c:return False# check if i,j share diagonal with any queenelif (i+j == c+r or i-j == c-r) and board[c][r] == 'q':return Falsereturn Truedef nQueens(r, n, board):# base case, when queens have been placed in all rows returnif r == n:return True, board# else in r-th row, check for every box whether it is suitable to place queenfor i in range(n):if isSafe(r, i, board):# if i-th columns is safe to place queen, place the queen there and check recursively for other rowsboard[r][i] = 'q'okay, newboard = nQueens(r+1, n, board)# if all next queens were placed correctly, recursive call should return true, and we should return true here tooif okay:return True, newboard# else this is not a suitable box to place queen, and we should check for next boxboard[r][i] = '-'return False, boarddef placeNQueens(n, board):return nQueens(0, n, board)[1]def main():n = 4board = [["-" for _ in range(n)] for _ in range(n)]qBoard = placeNQueens(n, board)qBoard = "\n".join(["".join(x) for x in qBoard])print (qBoard)main()
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 ...