Skip to content

Instantly share code, notes, and snippets.

@imouaddine
Created November 19, 2014 20:46
Show Gist options
  • Save imouaddine/fd7606904323bacd702c to your computer and use it in GitHub Desktop.
Save imouaddine/fd7606904323bacd702c to your computer and use it in GitHub Desktop.
a = [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
def is_safe(a, row, col, n)
#Check the same row
(0).upto(n-1) do |i|
if a[row][i] == 1
return false
end
end
i = row
j = col
while i >=0 && j >= 0
if a[i][j] == 1
return false
end
i -= 1
j -= 1
end
i = row
j = col
while i <n && j >= 0
if a[i][j] == 1
return false
end
i += 1
j -= 1
end
true
end
def n_queens_problem(a, col, n)
if col >= n
return true
end
(0).upto(n-1) do |row|
if is_safe(a, row, col, n)
a[row][col] = 1
puts a[row][col]
if n_queens_problem(a, col+1, n)
return true
end
#Back track
a[row][col] = 0
end
end
return false
end
puts n_queens_problem(a, 0,4)
puts a.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment