-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathn_queens.rb
54 lines (47 loc) · 1.37 KB
/
n_queens.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# https://leetcode.com/problems/n-queens/
#
# The n-queens puzzle is the problem of placing n queens on an n×n chessboard
# such that no two queens attack each other. Given an integer n, return all
# distinct solutions to the n-queens puzzle. Each solution contains a
# distinct board configuration of the n-queens' placement, where 'Q' and '.'
# both indicate a queen and an empty space respectively.
#
# For example, There exist two distinct solutions to the 4-queens puzzle:
#
# [
# [
# ".Q..", // Solution 1
# "...Q",
# "Q...",
# "..Q."
# ], [
# "..Q.", // Solution 2
# "Q...",
# "...Q",
# ".Q.."
# ]
# ]
# @param {Integer} n
# @return {String[][]}
def solve_n_queens(n)
[].tap do |result|
_solve_n_queens_(
Array.new(n, &Proc.new{ Array.new(n, '.') }), n, 0,
Array.new(n), Array.new(2 * n), Array.new(2 * n),
result
)
end
end
private def _solve_n_queens_(board, n, row, m1, m2, m3, result)
if row == n
result << board.map(&:join); return
end
0.upto(n - 1) do |col|
next if m1[col] || m2[row - col + n] || m3[row + col]
board[row][col] = 'Q'
m1[col] = m2[row - col + n] = m3[row + col] = true
_solve_n_queens_(board, n, row + 1, m1, m2, m3, result)
board[row][col] = '.'
m1[col] = m2[row - col + n] = m3[row + col] = false
end
end