Dennis Maina
Published on 15th June, 2023 (2 years ago)
N-Queens problem Technical Interview Question by FAANG
(1 minute read)
You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, column, or diagonal.
This is a popular question that is solved with backtracking. The following is a solution done in Python
def solve_n_queens(n):
def is_safe(board, row, col):
# Check if a queen can be placed at the given position without conflicting
# with any other queens on the board
for i in range(row):
if board[i] == col or \
board[i] - i == col - row or \
board[i] + i == col + row:
return False
return True
def backtrack(board, row):
# Base case: all queens have been placed successfully
if row == n:
return 1
count = 0
for col in range(n):
if is_safe(board, row, col):
board[row] = col
count += backtrack(board, row + 1)
board[row] = -1
return count
# Initialize the board with empty cells
board = [-1] * n
return backtrack(board, 0)
n = 4
count = solve_n_queens(n)
print(f"Number of possible arrangements for {n}-queens: {count}")
Comments (0)
Domain Name Registration & Hosting
HostPinnacle Kenya is the best and cheapest web hosting company in Kenya with world-class web hosting packages and affordable web design offers. Apart from that we offer free life-time SSL certificate, affordable domain registration in Kenya and free whois privacy. We have an award-winning support team available 24/7/365 to help you with your queries.
Ready to Elevate Your Digital Presence?
Whether you're looking to launch a cutting-edge mobile app, revamp your website with sustainable web design, or harness the power of AI and digital marketing to outshine your competition, we're here to turn your vision into reality. At DentriceDev, we blend innovation, expertise, and passion to deliver digital solutions that drive results. Don't let your business get left behind in the digital revolution. Reach out to us today, and let's create something remarkable together. Connect with us directly at info@dentricedev.com, give us a call or WhatsApp at +254 757 927190, or simply fill out our contact form to get started. Your digital future awaits, and we're excited to be part of your journey!