Fonction à lancer sudoku() . Résolution du jeu du sudoku avec saisie de la grille initiale a11 case en haut à gauche et case a99 en bas à droite. Si case vide saisir le chiffre 0. Algorithme perso qui repose sur le niveau d’hypothèse. Plus de confort police python en grand dans paramètres.
def pas_trouve_val(mat, val, ii, jj) : for k in range(9) : if val == mat[ii][k]%10 or val == mat[k][jj]%10 : return False icoin, jcoin = 3 * (ii//3), 3 * (jj//3) for k in range(icoin, icoin + 3) : for p in range (jcoin, jcoin + 3) : if val == mat[k][p] % 10 : return False return True def arriere (mat, nh) : a_rajouter = 0 for ir in range (9) : for jr in range (9) : if mat[ir][jr] // 10 == nh : mat[ir][jr] = 0 a_rajouter += 1 return (a_rajouter) def ajout_nh(mat, tabh): tabh.append([]) nbre_de_sol = 0 ih = 0 while ih < 9 : jh = 0 while jh < 9 : if mat[ih][jh] == 0 : for vv in range(1,10) : if pas_trouve_val(mat, vv, ih, jh) : nbre_de_sol += 1 ih , jh = 8 , 8 jh += 1 ih += 1 tabh[-1].append(nbre_de_sol) # nbre de valeurs possibles de 1ère case vide tabh[-1].append(0) # 0 valeur du premier indice ###### PROGRAMME PRINCIPAL ###### def sudoku(): #### SAISIE DE LA MATRICE GRILLE print ("Saisir la grille de départ") mat = [] ; acomp = 0 # acomp = à compléter for i in range(9): mat.append([]) for j in range(9): x = eval(input("a"+str(i+1)+str(j+1)+" = ")) mat[i].append(x) if x == 0 : acomp += 1 print("Grille de départ\n") for k in range(9) : print (mat[k]) print("\nNbre de cases à remplir =", acomp, "\n") tabh = [] ; tabh.append([]) # tabh table des hypothèses pile LIFO tabh[0].append(1) # colonne 1 : nbre de possibilités tabh[0].append(0) # colonne 2 : indice valeur à prendre # dans la table des solutions #### ALGORITHME DE RECHERCHE DES VALEURS A TROUVER flagnh = False while acomp > 0 : trouve = True while trouve : trouve = False ; i = 0 while i < 9 : j = 0 while j < 9 : if mat[i][j] == 0 : # on a repéré une case vide tabsol = [] # on construit la table des valeurs potentiellement # possibles (toutes ne seront pas possibles) for val in range(1,10) : if pas_trouve_val(mat, val, i, j) : tabsol.append(val + (len(tabh)-1)*10 ) if len(tabsol) == 1 : trouve = True ; flagnh = False mat[i][j] = tabsol[0] acomp -= 1 if len(tabsol)>1 and flagnh and len(tabh)>1 : # si len(tabh) > 1 trouve = True ; flagnh = False # on est dans les hypotheses mat[i][j] = tabsol[tabh[-1][1]] acomp -= 1 if len(tabsol) == 0 and len(tabh)>1 : trouve = True ; flagnh = True acomp += arriere(mat, len(tabh)-1) tabh[-1][1] += 1 while tabh[-1][1] >= tabh[-1][0] : del(tabh[-1]) acomp += arriere(mat, len(tabh)-1) tabh[-1][1] += 1 i , j = 8 , 8 j += 1 i += 1 # on sort de while trouve attention à l'indentation if acomp > 0 : # ajout d'un niveau hypothese ajout_nh(mat, tabh) flagnh = True #### MISE EN FORME ET IMPRESSION DES RESULTATS for ir in range (9): for jr in range (9): mat[ir][jr] %= 10 print("Grille complétée\n") for k in range(9): print (mat[k])