Skip to content

Instantly share code, notes, and snippets.

@itarato
Last active November 9, 2018 01:03
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 itarato/dd3e58a4bce5d2750748a9306c21241b to your computer and use it in GitHub Desktop.
Save itarato/dd3e58a4bce5d2750748a9306c21241b to your computer and use it in GitHub Desktop.
N-Queen with recursive and non-recursive algorithm
require 'pp'
def run_test
make_board = -> { 8.times.map { [0] * 8 } }
board = make_board.call
return false unless ok?(board)
board = make_board.call
board[0][0] = 1
board[0][1] = 1
return false if ok?(board)
board = make_board.call
board[0][0] = 1
board[1][0] = 1
return false if ok?(board)
board = make_board.call
board[0][0] = 1
board[1][1] = 1
return false if ok?(board)
board = make_board.call
board[0][1] = 1
board[1][0] = 1
return false if ok?(board)
true
end
def ok?(board)
return false unless 8.times.map { |i| board[i].sum }.all? { |sum| sum <= 1 }
return false unless 8.times.map { |i| 8.times.map { |j| board[j][i] }.sum }.all? { |sum| sum <= 1 }
return false unless (-7..7).map { |i| 8.times.map { |j| (i + j >= 0 && i + j < 8) ? board[j][i + j] : 0 }.sum }.all? { |sum| sum <= 1 }
return false unless (0..14).map { |i| 8.times.map { |j| (i - j >= 0 && i - j < 8) ? board[j][i - j] : 0 }.sum }.all? { |sum| sum <= 1 }
true
end
run_test ? (puts "TEST PASS") : exit
make_board = -> { 8.times.map { [0] * 8 } }
def solve_line_recursive(board, line = 0)
if line >= 8
pp board
return
end
8.times do |i|
if i > 0
board[line][i - 1] = 0
end
board[line][i] = 1
if ok?(board)
solve_line_recursive(board, line + 1)
end
end
board[line][7] = 0
end
def solve_line(board)
stack = [[0, 0]]
while stack.size > 0
row, col = stack.pop
if row >= 8
pp board
next
end
if col > 0
board[row][col - 1] = 0
end
is_ok = false
while !is_ok && col < 8
board[row][col] = 1
if ok?(board)
is_ok = true
stack.push([row, col + 1]) if col < 8
stack.push([row + 1, 0])
else
board[row][col] = 0
col += 1
end
end
end
end
solve_line_recursive(make_board.call)
solve_line(make_board.call)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment