簡體   English   中英

嘗試在Python中使用隨機數為數獨創建矩陣

[英]Trying create a matrix for sudoku with random numbers in Python

我需要創建一個數獨模板,並全部填充。 我需要處理隨機數,因此我檢查行和列中是否已經存在該數字。 問題在於,當在列中重復一個數字時,它不會嘗試另一個,從而導致無限循環。 有人能幫我嗎? 記住我需要處理隨機數。

import random
matrix = [[None for i in range(9)] for j in range(9)]

def criarSdk():
    for l in range(9):
        for c in range(9):
            if matrix[l][c] is None:
                tmp3 = False
                print("linha l={}, coluna c={}".format(l,c))
                while tmp3 is False:
                    ale = random.randint(1, 9)
                    tmp1 = veriLine(matrix,ale, l)
                    tmp2 = veriCol(matrix,ale, c)
                    tmp3 = tmp1 and tmp2
                    if tmp3 is True:
                        matrix[l][c] = ale

def veriLine(vetor, value, line):
    tmp = True
    for c in range(9):
        if value == vetor[line][c]:
            tmp = False

    return tmp

def veriCol(vetor, value, col):
    tmp = True
    for l in range(9):
        if value == vetor[l][col]:
            tmp = False

    return tmp

criarSdk()
for i in range(9):
    print(matrix[i])

您的問題不在於代碼,而在於算法。

如果這樣填充數獨,則可能會遇到無法在某些空間填充數字的情況。

考慮一下:

1 2 3 4 5 6 7 8 9
2 1 5 3 4 7 8 6 x

您可以想象第一行被隨機值填充(碰巧是按順序排列),然后第二行的值也被隨機值填充,但是要在x中輸入什么值? 您不能輸入9 ,因為它會在列上發生沖突。 但是您也不能輸入其他任何內容,因為其他所有內容都已在線上。

在這種情況下,您的代碼將無限循環,嘗試使用隨機數,但是它們都不起作用。

您需要研究回溯並提出更好的解決方案。 請注意,您需要隨機選擇一個數字並不一定意味着您繼續為新選項調用random.randint() ,也可以從尚未嘗試的一組數字中隨機選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM