编程语言
首页 > 编程语言> > 使用回溯的python中的Sudoku求解器

使用回溯的python中的Sudoku求解器

作者:互联网

我看到了几个数独求解器的实现,但是我无法在代码中找出问题所在.我有一个功能sudokusolver,它成为sudoku Board,必须返回已解决的sudoku board.

def sudokutest(s,i,j,z):
    # z is the number
    isiValid = np.logical_or((i+1<1),(i+1>9));
    isjValid = np.logical_or((j+1<1),(j+1>9));
    iszValid = np.logical_or((z<1),(z>9));
    if s.shape!=(9,9):
        raise(Exception("Sudokumatrix not valid"));
    if isiValid:
        raise(Exception("i not valid"));
    if isjValid:
        raise(Exception("j not valid"));
    if iszValid:
        raise(Exception("z not valid"));

    if(s[i,j]!=0):
        return False;

    for ii in range(0,9):
        if(s[ii,j]==z):
            return False;

    for jj in range(0,9):
        if(s[i,jj]==z):
            return False;

    row = int(i/3) * 3;
    col = int(j/3) * 3;
    for ii in range(0,3):
        for jj in range(0,3):
            if(s[ii+row,jj+col]==z):
                return False;

    return True;

def possibleNums(s , i ,j):
    l = [];
    ind = 0;
    for k in range(1,10):
        if sudokutest(s,i,j,k):
            l.insert(ind,k);
            ind+=1;
    return l;

def sudokusolver(S):
    zeroFound = 0;
    for i in range(0,9):
        for j in range(0,9):
            if(S[i,j]==0):
                zeroFound=1;
                break;
        if(zeroFound==1):
            break;
    if(zeroFound==0):
          return S;

    x = possibleNums(S,i,j);
    for k in range(len(x)):
        S[i,j]=x[k];
        sudokusolver(S);
    S[i,j] = 0;
    sudokusolver(S);
    return S;

sudokutest和possibleNums是正确的,只有sudokusolver给出RecursionError

解决方法:

在最后三行中:

S[i,j] = 0;
sudokusolver(S);
return S;

您总是会重置更改,因此将永远不会填充S.最后不需要递归.

标签:sudoku,python,artificial-intelligence
来源: https://codeday.me/bug/20191010/1886112.html