Как реализовать рекурсию при поиске уникального судоку (python)? - PullRequest
0 голосов
/ 07 августа 2020

Я пытаюсь написать функцию с рекурсией, но каждый раз я получаю пустой результат ... Код следующий: сначала создается случайная сетка (random_puzzle()). Он преобразуется из строки в массив, после чего решается и проверяется, уникальна ли созданная судоку (solve(grid)). Я хочу, чтобы код продолжал создавать новые судоку, пока не найдет уникальную головоломку. Почему моя рекурсия не работает? Заранее спасибо!

grids={}
Grids={}
final_grid = []

def solve(grid):
    global uniq, count, proc_time
    tic = time.perf_counter()
    if uniq < 2:
        for y in range(9):
            for x in range(9):
                if grid[y][x] == 0: 
                    for n in range(1,10):
                        if possible(y,x,n):
                            grid[y][x] = n 
                            solve(grid)
                            count += 1
                            grid[y][x] = 0
                    return grid
                
    uniq += 1
    toc = time.perf_counter()
    proc_time = toc - tic
#     print('Time needed to solve Sudoku: '+str(toc - tic)+' seconds')
#     print('Steps needed:'+str(count))
    return grid

def random_puzzle(N=25):
    values = dict((s, digits) for s in squares)
    for s in shuffled(squares):
        if not assign(values, s, random.choice(values[s])):
            break
        ds = [values[s] for s in squares if len(values[s]) == 1]
        if len(ds) >= N and len(set(ds)) >= 8:
            return ''.join(values[s] if len(values[s])==1 else '.' for s in squares)
    return random_puzzle(N) 


def make_grid():
    uniq=0
    count=0
    Grids=random_puzzle(N=25)
    mat = Grids.replace('.','0')
    grid = np.zeros([9,9])
    countx = 0 
    county = 0
    for j in mat:
        if countx >= 8:
            grid[county,countx] = j 
            countx = 0
            county += 1
        else:
            grid[county,countx] = j
            countx += 1   
    final_grid = solve(grid)
    if  uniq > 1:
        make_grid()          
    elif uniq == 1: 
        return final_grid

test = make_grid()
print(test)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...