Skip to content

Instantly share code, notes, and snippets.

@tacigar
Created March 9, 2018 13:16
Show Gist options
  • Save tacigar/e44ad789822ff85fb77096f760bad476 to your computer and use it in GitHub Desktop.
Save tacigar/e44ad789822ff85fb77096f760bad476 to your computer and use it in GitHub Desktop.
local field = {}
for i = 1, 9 do
local buf = io.read()
field[i] = {}
for j = 1, 9 do
field[i][j] = tonumber(buf:sub(j, j))
end
end
local function print_field(field)
for i = 1, 9 do
for j = 1, 9 do
if field[i][j] == nil then
io.write(". ")
else
io.write(tostring(field[i][j]) .. " ")
end
if j % 3 == 0 then
if j ~= 9 then
io.write("| ")
else
io.write("\n")
end
end
end
if i % 3 == 0 and i ~= 9 then
io.write(("-"):rep(6).."+"..("-"):rep(7).."+"..("-"):rep(6).."\n")
end
end
end
function solve(field, xi, yi)
xi = xi or 1
yi = yi or 1
if yi > 9 then
return true
elseif field[yi][xi] ~= nil then
if xi == 9 then
if solve(field, 1, yi + 1) then
return true
end
else
if solve(field, xi + 1, yi) then
return true
end
end
else
for i = 1, 9 do
if check(field, xi, yi, i) then
field[yi][xi] = i
if xi == 9 then
if solve(field, 1, yi + 1) then
return true
end
else
if solve(field, xi + 1, yi) then
return true
end
end
end
end
field[yi][xi] = nil
return false
end
return false
end
function check(field, xi, yi, i)
for j = 1, 9 do
if field[yi][j] == i then
return false
end
end
for j = 1, 9 do
if field[j][xi] == i then
return false
end
end
local xb = ((xi - 1) // 3) * 3 + 1
local yb = ((yi - 1) // 3) * 3 + 1
for xii = xb, xb + 2 do
for yii = yb, yb + 2 do
if field[yii][xii] == i then
return false
end
end
end
return true
end
local b = solve(field)
print_field(field)
@tacigar
Copy link
Author

tacigar commented Nov 19, 2020

Example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment