Skip to content

Instantly share code, notes, and snippets.

@dhilst
Created September 18, 2019 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhilst/af9d5c15df94e0b36a8787c42ffab0ca to your computer and use it in GitHub Desktop.
Save dhilst/af9d5c15df94e0b36a8787c42ffab0ca to your computer and use it in GitHub Desktop.
In [1]: for q2 in range (1, len(board)-q1):
...: if board[q1] == board[q1+q2] or board[q1+q2] == board[q1]+q2
...: or board[q1+q2] == board[q1]-q2:
...: return False
...: return True
...:
...: def n_queens_solutions(n):
...: board = []
...: return n_queens_helper(0, board, n)
...:
...: def n_queens_helper(n, board, size):
...: if len(board) == size:
...: print(board)
...: yield board
...: else:
...: for i in range(size):
...: board.append(i)
...: if n_queens_valid(board):
...: yield from n_queens_helper(n+1, board, size)
...: board.pop()
...:
...: print(list(n_queens_solutions(4)))
...:
...:
[1, 3, 0, 2]
[2, 0, 3, 1]
[[], []]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment