求解n宮數獨

2021-09-11 03:06:13 字數 2477 閱讀 3174

def show(a, n):#輸出結果

for i in range(n):

for j in range(n):

print(a[i][j], end=" ")

print()

print()

import copy

def sudoku(a, n):

def is_ok(b, n):

def answer(r, c):

t = [0] * (n + 1)

for i in range(n):#標記同行同列的已有數字

t[b[r][i]], t[b[i][c]] = 1, 1

s = int(n ** 0.5)#每個宮的尺寸

#確定a[r][c]所在宮的起始行列座標

br, bc = (r // s) * s, (c // s) * s

for i in range(br, br+s):#標記同宮已有數字

for j in range(bc, bc+s):

t[b[i][j]] = 1

k = 0

for i in range(1, n+1):

if t[i] == 0:

num = i

else:

k += 1 #累計已有數字

if k == n - 1: #b[r][c]的值確定為num

return num

else:

return 0

flag = false

while not flag:

flag = true

for r in range(n):

for c in range(n):

if b[r][c] == 0:

b[r][c] = answer(r, c)

if b[r][c] > 0:

flag = false

#判定是否已經有解

for i in range(n):

for j in range(n):

if b[i][j] == 0:

return false

return true

def dfs(r, c):

nonlocal count

b = copy.deepcopy(a)

if is_ok(b, n) or r == n: #所有位置都填好了,輸出解

count += 1

print(f':')

show(b, n)

elif a[r][c] > 0:#該位置的值已確定,直接下一步

if c < n - 1:#確定下乙個位置的座標

tr, tc = r, c + 1

else:

tr, tc = r + 1, 0

dfs(tr, tc) 

else:

for i in range(1, n+1):#列舉本位置的可能取值

if check(a, n, r, c, i):#如果可以取數字i,遞迴進入下一層

a[r][c] = i

if c < n - 1:

tr, tc = r, c + 1

else:

tr, tc = r + 1, 0

dfs(tr, tc)

a[r][c] = 0 #所有數字都取過了,恢復原值,回溯

count = 0

dfs(0, 0)

a = [[0,1,0,0],

[0,0,0,0],

[0,0,3,0],

[0,2,0,0]]

n = 4

show(a, n)

sudoku(a, n)

print()

a = [[1,0,8,0,0,4,0,5,0],

[0,0,4,0,3,7,0,0,2],

[0,0,2,0,0,6,4,3,0],

[0,0,1,0,9,0,0,0,4],

[5,7,0,4,8,0,0,6,3],

[4,0,0,0,5,0,8,0,0],

[0,9,5,1,0,0,3,0,0],

[8,0,0,2,6,0,7,0,0],

[0,1,0,3,0,0,9,0,8]]

n = 9

show(a, n)

sudoku(a, n)

print()

a = [[1,3,0,0,0,4,0,5,0],

[0,0,4,0,0,0,0,0,2],

[0,0,2,0,0,6,4,3,0],

[0,2,1,0,9,0,0,0,4],

[5,7,0,0,0,0,0,6,3],

[4,0,0,0,5,0,8,0,0],

[0,0,0,1,0,0,3,0,0],

[8,0,0,0,0,0,7,0,0],

[0,1,5,3,8,0,0,0,6]]

n = 9

show(a, n)

sudoku(a, n)

數獨(Sudoku)求解程式

數獨完全求解程式 ver 3.0 coolypf 2008 11 24 22 11 include using namespace std int matrix 9 9 數獨矩陣 int count 0 解的個數 int check int x,int y,bool mark 10 檢測matrix...

數獨高階版求解

請你將乙個16x16的數獨填寫完整,使得每行 每列 每個4x4十六宮格內字母a p均恰好出現一次。保證每個輸入只有唯一解決方案。輸入格式 輸入包含多組測試用例。每組測試用例包括16行,每行一組字串,共16個字串。第i個字串表示數獨的第i行。字串包含字元可能為字母a p或 表示等待填充 測試用例之間用...

數獨求解程式 PHP暴力求解

數獨求解程式 class sudoku else function clear function setcell row,col,value col for i 0 i 9 i square rs intval row 3 3 cs intval col 3 3 for i rs i rs 3 i ...