「8 皇后問題」(Ruby 版)

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章