Skip to main content

N-Queens Problem

Definition​

The N-Queens Problem is a classic computer science problem where the task is to place N chess queens on an NxN chessboard in such a way that no two queens threaten each other. This means that no two queens share the same row, column, or diagonal

Practice​

solveNQueens(board, row):
if row == size_of_board:
return true // all queens are placed successfully
for each column in size_of_board:
if isSafe(board, row, column):
placeQueen(board, row, column)
if solveNQueens(board, row + 1):
return true
removeQueen(board, row, column)
return false // no solution found

isSafe(board, row, column):
for i from 0 to row - 1:
if board[i][column] == true:
return false // queen threatens in the same column
if column - (row - i) >= 0 and board[i][column - (row - i)] == true:
return false // queen threatens in the left diagonal
if size_of_board > column + (row - i) and board[i][column + (row - i)] == true:
return false // queen threatens in the right diagonal
return true

placeQueen(board, row, column):
board[row][column] = true

removeQueen(board, row, column):
board[row][column] = false