Last active
July 24, 2017 03:39
-
-
Save obelisk68/97c164072dbc1d86084ae32732ba4cfe to your computer and use it in GitHub Desktop.
This file contains 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
N = 8 | |
class EightQueen | |
class Step | |
def initialize(x, y) | |
@x, @y = x, y | |
@parent = nil | |
@depth = 0 | |
end | |
attr_accessor :x, :y, :parent, :depth | |
end | |
def initialize(x, y) | |
@stack = [Step.new(x, y)] | |
@num = 0 | |
end | |
def solve | |
while (a = @stack.pop) | |
y = a.y + 1 | |
board = get_board(a) | |
N.times do |x| | |
next if board[y][x] == 1 | |
nxt = Step.new(x, y) | |
nxt.parent = a | |
nxt.depth = a.depth + 1 | |
if nxt.depth == N - 1 | |
answer(nxt) | |
else | |
@stack.push(nxt) | |
end | |
end | |
end | |
@num | |
end | |
def get_board(a) | |
board = Array.new(N) {Array.new(N, 0)} | |
begin | |
N.times do |i| | |
board[i][a.x] = 1 | |
board[i] = Array.new(N, 1) if i == a.y | |
d = (i - a.y).abs | |
next if d.zero? | |
x1 = a.x - d | |
x2 = a.x + d | |
board[i][x1] = 1 if x1 >= 0 | |
board[i][x2] = 1 if x2 < N | |
end | |
end while (a = a.parent) | |
board | |
end | |
def answer(a) | |
bd = Array.new(N) {"." * N} | |
while a | |
bd[a.y][a.x] = "@" | |
a = a.parent | |
end | |
bd.map {|x| puts x} | |
puts "---------" | |
@num += 1 | |
end | |
end | |
num = 0 | |
N.times {|i| num += EightQueen.new(i, 0).solve} | |
puts "\n#{num} answers." |
This file contains 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
$ time ruby eight_queen_all.rb | |
(omit)... | |
--------- | |
.......@ | |
.@...... | |
...@.... | |
@....... | |
......@. | |
....@... | |
..@..... | |
.....@.. | |
--------- | |
92 answers. | |
real 0m0.146s | |
user 0m0.092s | |
sys 0m0.016s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment