Search⌘ K

Solution: Eight Queens Puzzle

Explore how to implement the eight queens puzzle solution in Ruby by applying recursion and backtracking. Understand the use of instance variables, helper methods, and constraint checks to place queens on a chessboard correctly.

Eight queens puzzle

Ruby
def print_chessboard
@chessboard.length.times do |i|
puts " #{@chessboard[i].join(" | ")}"
puts "--- " * @chessboard[i].size
end
end
# calculating diagonal values
def get_diagonal_values pos
diagonals = []
len = @chessboard.length
@chessboard.length.times do |i|
neg_x = pos[0] - i
neg_y = pos[1] - i
pos_x = pos[0] + i
pos_y = pos[1] + i
diagonals << @chessboard[neg_x][neg_y] if neg_x >= 0 && neg_y >= 0
diagonals << @chessboard[neg_x][pos_y] if neg_x >= 0 && pos_y < len
diagonals << @chessboard[pos_x][neg_y] if neg_y >= 0 && pos_x < len
end
return diagonals
end
def check_constraints pos
diagonals = get_diagonal_values(pos)
@chessboard[pos[0]].all? { | x | x == "." } && # no queen in same row
@chessboard.collect { | sqr | sqr[pos[1]] }.all? { | x | x == "." } && # no queen in same column
diagonals.all? { | x | x == "." } && # no queen in all diagonals
@chessboard[pos[0]][pos[1]] == "." # unvisited location
end
@queens = 0
@max_queens = 8
@chessboard = Array.new(8){ Array.new(8, '.')}
def place_queens row
@chessboard[row][@queens] = "Q" # placing queen in chessboard
@queens += 1
# end cause
if @queens == @max_queens
print_chessboard
exit
end
# trying all possible locations in a row
@chessboard.length.times do |row_item|
place_queens(row_item) if check_constraints([row_item, @queens]) # only place queen when constraints are met
end
# backtracking
@queens -= 1
@chessboard[row][@queens] = "."
end
@chessboard.length.times do |x|
place_queens(x)
end
# loop ended without finding a solution
puts "Solution not found!"

Explanation

Instance variables

The role of instance variables in the code (lines 37–39) is:

  • @chessboard is initialized to an array of size 8, such that each of its elements is also an array of size 8 (representing a chess board row) containing . characters. ...