Generate All Nonattacking Placements of n -Queens
Given n queens on an n × n chessboard, compute all nonattacking placements.
Nonattacking placement = no two queens can threaten each other:
Queens can't be in same row
Queens can't be in same column
Queens can't be in same diagonal
Input: n = 4
Output: [[1, 3, 0, 2], [2, 0, 3, 1]]
def n_queens (n ):
def dfs (queens , xy_diff , xy_sum ):
row = len (queens )
if row == n :
result .append (queens )
for col in range (n ):
if col not in queens and row - col not in xy_diff and row + col not in xy_sum :
dfs (queens + [col ], xy_diff + [row - col ], xy_sum + [row + col ])
result = []
dfs ([], [], [])
return result
For any point (x , y ), if the new point (p , q ) shouldn't share the same row, column, or diagonal, then we must have:
p + q != x + y : eliminate left bottom right top diagonal
p - q != x - y : eliminate left top right bottom diagonal
Set the row as the length of queens , which is the list of column index per row
If the current row is equal to n , then add it to queens
if row == n :
result .append (queens )
For any point (x , y ), find a new point (p , q ) that does not share the same row, column, or diagonal
for col in range (n ):
if col not in queens and row - col not in xy_diff and row + col not in xy_sum :
dfs (queens + [col ], xy_diff + [row - col ], xy_sum + [row + col ])
queens
the list of column index per row
row
the current row where we're searching for a valid column
xy_diff
the list of x - y
xy_sum
the list of x + y
Code Dissection - n_queens
Create a list to hold the result, run dfs()
with empty lists as the input, then return the result
result = []
dfs ([], [], [])
return result