Skip to content

Instantly share code, notes, and snippets.

@obelisk68
Last active July 24, 2017 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obelisk68/97c164072dbc1d86084ae32732ba4cfe to your computer and use it in GitHub Desktop.
Save obelisk68/97c164072dbc1d86084ae32732ba4cfe to your computer and use it in GitHub Desktop.
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."
$ 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