Created
January 2, 2017 08:00
-
-
Save bananaumai/720f162a33383f8e79e8035b2bc36982 to your computer and use it in GitHub Desktop.
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
require 'set' | |
COL_NUM = 8 | |
def queen() | |
place([], 1, COL_NUM).select{ |l| l.length == 8 } | |
end | |
def place(accum, col, col_num) | |
available_squares = find_available_squares(accum, col_num) | |
return available_squares.map{ |square| accum + [square] } if col == col_num | |
return [accum] if available_squares.empty? | |
return available_squares.flat_map{ |square| place(accum + [square], col+1, col_num) } | |
end | |
def find_available_squares(selected_squares, col_num) | |
squares = (1..col_num).to_a | |
current_col = selected_squares.length + 1 | |
selected_squares.each_with_index do |place, i| | |
diff_between_cols = current_col - (i + 1) | |
squares.delete(place + diff_between_cols) # 斜め下方向のセルを排除 | |
squares.delete(place - diff_between_cols) # 斜め上方向のセルを排除 | |
squares.delete(place) # 同一行のセルを排除 | |
end | |
squares | |
end | |
puts "組み合わせ数: #{queen().length}" | |
queen().each {|pat| p pat} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment