Skip to content

Instantly share code, notes, and snippets.

@jac18281828
Created May 12, 2025 23:01
Show Gist options
  • Save jac18281828/0f553a750c51d524f77fac3d4ae2174f to your computer and use it in GitHub Desktop.
Save jac18281828/0f553a750c51d524f77fac3d4ae2174f to your computer and use it in GitHub Desktop.
eight queens problem hacker rank
from typing import Tuple
class InvalidGame(Exception):
def __init__(self, message):
super().__init__(message)
class Board:
"""N x N chessboard"""
N = 8
def __init__(self):
"""get the party started"""
# queen_col[x] = y means a queen is at (x, y)
self.queen_col = [-1] * (Board.N + 1)
# track column occupancy
self.columns = [False] * (Board.N + 1)
# x + y ranges 2..16 → we index 0..16
self.diag1 = [False] * (Board.N * 2 + 1)
# x - y ranges -7..+7 → shift by (N−1)=7 to index 0..14
self.diag2 = [False] * (Board.N * 2)
def _place_queen_recursive(self, n_queen: int, row: int) -> bool:
if row > n_queen:
return True
for col in range(1, Board.N + 1):
if self.check_queen((row, col)):
self.set_queen((row, col))
if self._place_queen_recursive(n_queen, row + 1):
return True
self.clear_queen((row, col))
return False
def place_queens(self, n_queen: int) -> bool:
if n_queen > Board.N:
raise InvalidGame(f"Can not place {n_queen} queens on a board of {Board.N}")
return self._place_queen_recursive(n_queen, 1)
def set_queen(self, position: Tuple[int, int]) -> None:
x, y = position
self.queen_col[x] = y
self.columns[y] = True
self.diag1[x + y] = True
self.diag2[x - y + Board.N - 1] = True
def check_queen(self, position: Tuple[int, int]) -> bool:
x, y = position
if self.columns[y]:
return False
if self.diag1[x + y]:
return False
if self.diag2[x - y + Board.N - 1]:
return False
return True
def clear_queen(self, position: Tuple[int, int]) -> None:
x, y = position
self.queen_col[x] = -1
self.columns[y] = False
self.diag1[x + y] = False
self.diag2[x - y + Board.N - 1] = False
@staticmethod
def is_valid_placement(position: Tuple[int, int]) -> bool:
x, y = position
return 0 < x <= Board.N and 0 < y <= Board.N
if __name__ == "__main__":
board = Board()
if board.place_queens(8):
print("Found a valid configuration:\n")
for r in range(1, Board.N + 1):
row_str = ""
c = board.queen_col[r]
for col in range(1, Board.N + 1):
row_str += "Q " if col == c else ". "
print(row_str.strip())
else:
print("No solution found.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment