Skip to content

Instantly share code, notes, and snippets.

@matsumotius
Created January 8, 2012 05:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsumotius/1577299 to your computer and use it in GitHub Desktop.
Save matsumotius/1577299 to your computer and use it in GitHub Desktop.
8queen
def eight_queen(n = 8, m = 8)
run(n, m, [])
end
def run(kinds, len, a)
return unless can_set_queen?(a)
if len == 0 then
puts a.join(',')
else
kinds.times { |i|
run(kinds,len-1,a+[i])
}
end
end
def can_set_queen?(a)
return false if a.size != a.uniq.size
a.each_with_index do |v, i|
a.each_with_index do |vv, ii|
next if i == ii
diff = i - ii
return false if vv == v - diff or vv == v + diff
end
end
return true
end
eight_queen()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment