Skip to content

Instantly share code, notes, and snippets.

@manoamaro
Created June 2, 2013 19:15
Show Gist options
  • Save manoamaro/5694550 to your computer and use it in GitHub Desktop.
Save manoamaro/5694550 to your computer and use it in GitHub Desktop.
Sudoku solver by backtracking algorithm
require 'matrix'
class Matrix
# Assign the given value to the slot at the specified row and column
def []=(row, column, value)
@rows[row][column] = value
end
def to_s
[sprintf("%d x %d Matrix", @rows.length, column_size),
@rows.map { |row| row.inspect }].flatten.join("\n")
end
end
grid = Matrix.rows([
[8,0,0,0,0,0,0,0,0],
[0,0,3,6,0,0,0,0,0],
[0,7,0,0,9,0,2,0,0],
[0,5,0,0,0,7,0,0,0],
[0,0,0,0,4,5,7,0,0],
[0,0,0,1,0,0,0,3,0],
[0,0,1,0,0,0,0,6,8],
[0,0,8,5,2,0,0,1,0],
[0,9,0,0,0,0,4,0,0]
])
puts grid
def solve_sudoku(grid)
return true if grid.index(0).nil?
actual = grid.index(0)
(1..9).each do |n|
next if grid.row(actual[0]).include?(n) || grid.column(actual[1]).include?(n) || verify_blocks(grid, actual, n)
grid[actual[0], actual[1]] = n
if solve_sudoku(grid)
return true
end
end
grid[actual[0], actual[1]] = 0
return false
end
def verify_blocks(grid, actual, value)
block_row_start = actual[0] - (actual[0] % 3)
block_column_start = actual[1] - (actual[1] % 3)
block_row_end = block_row_start + (3 - 1)
block_column_end = block_column_start + (3 - 1)
(block_row_start..block_row_end).each do |r|
(block_column_start..block_column_end).each do |c|
return true if grid[r,c] == value
end
end
return false
end
solve_sudoku(grid)
puts grid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment