Last active
April 10, 2016 19:27
-
-
Save vasuadari/565b04530132d970fadcfd2b0937ffd4 to your computer and use it in GitHub Desktop.
NQueen
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
#! /usr/bin/env ruby | |
# Author: Vasu Adari(vasuakeel@gmail.com) | |
# Problem: Solve NQueen using Backtracking algorithm. | |
def safe?(array, row, col) | |
col.times.any? { |i| array[row][i] } && return | |
(size = array.size).times do |i| | |
((row - i) < 0) || ((col - i) < 0) ? next : array[row - i][col - i] && return | |
(row + i) >= size ? next : array[row + i][col - i] && return | |
end | |
true | |
end | |
def solve_n_queen(array, col = 0) | |
return true if col >= (n = array.size) | |
n.times do |i| | |
if safe?(array, i, col) | |
array[i][col] = 1 | |
return true if solve_n_queen(array, col + 1) | |
array[i][col] = nil | |
end | |
end | |
false | |
end | |
def n_queen(n = 8) | |
array = [*1..n].map { [*1..n].map { } } | |
solve_n_queen(array) | |
array.each { |a| p a.map &:to_i } | |
end | |
n_queen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment