python 解决6*6的数独

朋友家的小侄子上中班,学校竟然就布置数独题目,真狠!!!

虽然是6*6,快乐暑假不快乐了!!!!

在9*9的数独程序中略作修改,

话不多说,直接上代码!

import numpy as np
import time
time1 = time.time()

 
def six(data):
    six_block = np.zeros([2,3,3,2], dtype = int)
    for i in range(2):
        for j in range(3):
            six_block[i,j] = data[3*i:3*(i+1),2*j:2*(j+1)]
    return six_block
 
def num_set(data, six_block):
    pick_set = {}
    for i in range(6):
        for j in range(6):
            if data[i,j] == 0:
                pick_set[str(i)+str(j)] = set(np.array(range(7))) - \
                (set(data[i,:]) | set(data[:,j]) | \
                set( six_block [i//3,j//2].ravel()))
    return pick_set
 
 
def try_insert(data):    
 
    insert_step = []
    while True:
        
        pick_set = num_set(data, six(data))
        if len(pick_set) == 0: break
        pick_sort = sorted(pick_set.items(), key = lambda x:len(x[1]))
        item_min = pick_sort[0]
        key = item_min[0]
        value = list(item_min[1])
        insert_step.append((key, value))
        if len(value) != 0:
            data[int(key[0]), int(key[1])] = value[0]
        else:
            insert_step.pop()
            for i in range(len(insert_step)):
                huishuo = insert_step.pop()
                key = huishuo[0]
                insert_num = huishuo[1]
                if len(insert_num) == 1:
                    data[int(key[0]), int(key[1])] = 0
                else:
                    data[int(key[0]), int(key[1])] = insert_num[1]
                    insert_step.append((key, insert_num[1:]))
                    break
    tiem2 = time.time()
    print('\nFinished! using time:', tiem2-time1, 's')
    print(data)    
   
if __name__ == '__main__':
    data =  "0 0 0 0 6 0 \
             1 0 0 0 0 0 \
             0 2 0 6 0 4 \
             3 0 1 0 4 0 \
             0 0 0 0 0 5 \
             0 4 0 0 0 0  "
    data = np.array(data.split(), dtype = int).reshape((6, 6))
    print(data)
    try_insert(data)

 

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用回溯算法来解决数独问题,以下是一个用Python实现的数独解决器: ```python def solve_sudoku(board): """ Solves a given Sudoku board. :param board: a 9x9 list of integers representing the Sudoku board :return: True if the board is solvable, False otherwise """ # Find the next empty cell row, col = find_empty_cell(board) # If there are no empty cells, the board must be solved if row is None: return True # Try every possible number for the empty cell for num in range(1, 10): if is_valid_move(board, row, col, num): board[row][col] = num # Recursively solve the rest of the board if solve_sudoku(board): return True # If the recursive call did not find a solution, backtrack board[row][col] = 0 # If no number works for the empty cell, the board is unsolvable return False def find_empty_cell(board): """ Finds the first empty cell on the board. :param board: a 9x9 list of integers representing the Sudoku board :return: a tuple (row, col) of the first empty cell, or None if the board is full """ for row in range(9): for col in range(9): if board[row][col] == 0: return row, col return None, None def is_valid_move(board, row, col, num): """ Checks if a given move is valid for the given board. :param board: a 9x9 list of integers representing the Sudoku board :param row: the row of the cell being filled :param col: the column of the cell being filled :param num: the number being placed in the cell :return: True if the move is valid, False otherwise """ # Check the row if num in board[row]: return False # Check the column if num in [board[i][col] for i in range(9)]: return False # Check the 3x3 square square_row = (row // 3) * 3 square_col = (col // 3) * 3 if num in [board[i][j] for i in range(square_row, square_row + 3) for j in range(square_col, square_col + 3)]: return False # If all checks pass, the move is valid return True ``` 你可以将一个数独题目表示成一个9x9的列表,其中空白格子用0表示。例如,下面是一个数独题目的表示: ``` [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ] ``` 调用`solve_sudoku`函数将会在原地修改这个列表,使其变成数独的解(如果有解)。如果数独无解,函数将返回False。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CZU_zzjj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值