-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path052.rb
More file actions
65 lines (58 loc) · 1.46 KB
/
052.rb
File metadata and controls
65 lines (58 loc) · 1.46 KB
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
55
56
57
58
59
60
61
62
63
64
65
def is_valid(board, row, col)
return false if board[row].each_with_index.any? do |item, c|
c != col && item
end
return false if board.each_with_index.any? do |line, r|
r != row && line[col]
end
if row >= col
return false if (row - col).upto(board.length - 1).any? do |r|
c = r - row + col
r != row && board[r][c]
end
else
return false if 0.upto(board.length - 1 - col + row).any? do |r|
c = col - row + r
r != row && board[r][c]
end
end
if row + col < board.length
return false if 0.upto(row + col).any? do |r|
c = row + col - r
r != row && board[r][c]
end
else
return false if (row + col - board.length + 1).upto(board.length - 1).any? do |r|
c = row + col - r
r != row && board[r][c]
end
end
true
end
def find_solution board, row, results
if row == board.length
sum = 0
board.each do |line|
line.each do |item|
sum += 1 if item
end
end
results.push(board.map{|line| line.map {|item| item ? "Q" : "."}.join("")}) if sum == board.length
return
end
0.upto(board.length - 1).each do |col|
next unless is_valid(board, row, col)
board[row][col] = true
find_solution(board, row + 1, results)
board[row][col] = false
end
end
# @param {Integer} n
# @return {Integer}
def total_n_queens(n)
board = []
1.upto(n).each { board.push(Array.new(n, false)) }
results = []
find_solution(board, 0, results)
results.length
end