Lingo编写数独求解器
时间: 2024-05-07 17:19:50 浏览: 9
好的,以下是一个简单的 Lingo 程序,可以解数独:
```
-- 数独谜题(0 表示空格)
puzzle = [[5, 0, 0, 0, 0, 0, 6, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 2],
[0, 1, 9, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
-- 检查行是否合法
function check_row(puzzle, row, num)
for i = 1 to 9 do
if puzzle[row][i] = num then
return false
end if
end for
return true
end
-- 检查列是否合法
function check_col(puzzle, col, num)
for i = 1 to 9 do
if puzzle[i][col] = num then
return false
end if
end for
return true
end
-- 检查九宫格是否合法
function check_box(puzzle, row, col, num)
box_row = int((row - 1) / 3) * 3 + 1
box_col = int((col - 1) / 3) * 3 + 1
for i = box_row to box_row + 2 do
for j = box_col to box_col + 2 do
if puzzle[i][j] = num then
return false
end if
end for
end for
return true
end
-- 检查是否可以填入数字
function can_place(puzzle, row, col, num)
return check_row(puzzle, row, num) and
check_col(puzzle, col, num) and
check_box(puzzle, row, col, num)
end
-- 查找下一个空格
function find_empty(puzzle)
for i = 1 to 9 do
for j = 1 to 9 do
if puzzle[i][j] = 0 then
return i, j
end if
end for
end for
return 0, 0
end
-- 递归求解数独
function solve(puzzle)
row, col = find_empty(puzzle)
if row = 0 and col = 0 then
return true
end if
for num = 1 to 9 do
if can_place(puzzle, row, col, num) then
puzzle[row][col] = num
if solve(puzzle) then
return true
end if
puzzle[row][col] = 0
end if
end for
return false
end
-- 显示数独谜题和解法
on mouseUp
put "Puzzle:" && cr after msg
repeat with i = 1 to 9
put puzzle[i] after msg
put cr after msg
end repeat
put cr & "Solution:" & cr after msg
solve(puzzle)
repeat with i = 1 to 9
put puzzle[i] after msg
put cr after msg
end repeat
end mouseUp
```
程序中,首先定义了一个数独谜题(0 表示空格)。然后定义了检查行、列和九宫格是否合法的三个函数,以及检查是否可以填入数字的函数、查找下一个空格的函数和递归求解数独的函数。最后在 `on mouseUp` 事件中调用这些函数,显示数独谜题和解法。
运行程序后,点击鼠标即可看到数独谜题和解法。