「8 皇后问题」(Ruby 版)
2022-07-08 本文已影响0人
Pope怯懦懦地
45 行搞定✌🏻。
require "set"
def is_nth_valid?(states, row)
return true if states.empty?
# 假设 states 已经检查过了,没问题的。
n = states.size
# chech the rows
rows_valid = (Set.new([states, row].flatten).size == n + 1)
return false unless rows_valid
# check the columns
# check the diagonal
# 0
# 1
# 2
# 3
# 4
# 5 4 3 2 1 0
diagonal_valid = true
states.each_with_index do |s, i|
diagonal_valid &&= ((s - row).abs != n + 1 - (i + 1))
return false unless diagonal_valid
end
return rows_valid && diagonal_valid
end
def find_8_Q_solution(n)
return (0..7).to_a.map { |e| [e] } if n == 1
solutions = []
find_8_Q_solution(n - 1).each do |states_n_1|
8.times do |row|
if is_nth_valid?(states_n_1, row)
solutions << [states_n_1, row].flatten
else
next
end
end
end
solutions
end
p find_8_Q_solution(8).size #=> 92