Created
April 4, 2024 03:57
-
-
Save codertcet111/0b48afd8d1b5bca92b8cc7080a989797 to your computer and use it in GitHub Desktop.
Leetcode 51 N queen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Leetcode 51 N queen | |
def solve_n_queens(n) | |
@n = n | |
@solutions = [] | |
board = Array.new(n) { Array.new(n, '.') } | |
place_queens(board, 0) | |
@solutions | |
end | |
def place_queens(board, row) | |
if row == @n | |
@solutions << board.map(&:join) | |
return | |
end | |
(0...@n).each do |col| | |
if valid_move?(board, row, col) | |
board[row][col] = 'Q' | |
place_queens(board, row + 1) | |
board[row][col] = '.' | |
end | |
end | |
end | |
def valid_move?(board, row, col) | |
# Check the column | |
(0...row).each { |i| return false if board[i][col] == 'Q' } | |
# Check upper-left diagonal | |
i, j = row - 1, col - 1 | |
while i >= 0 && j >= 0 | |
return false if board[i][j] == 'Q' | |
i -= 1 | |
j -= 1 | |
end | |
# Check upper-right diagonal | |
i, j = row - 1, col + 1 | |
while i >= 0 && j < @n | |
return false if board[i][j] == 'Q' | |
i -= 1 | |
j += 1 | |
end | |
true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment