You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python回溯法数独求解器如何适配无逗号分隔的字符串输入

解决方案

你原有的数独求解逻辑无需修改,只需新增输入转换步骤,将9位连续数字字符串的输入格式转换为现有代码兼容的嵌套整数列表即可,具体实现如下:

1. 核心转换逻辑

新增输入转换函数:

def str_to_board(input_lines):
    # input_lines是9个元素的列表,每个元素为9位数字字符串
    return [[int(char) for char in line.strip()] for line in input_lines]

2. 适配输入样例的使用示例

针对你给出的输入样例,替换原有硬编码的board定义即可:

# 输入样例,也可从本地文件读取
input_sudoku = [
    "003020600",
    "900305000",
    "001806400",
    "008102900",
    "700000008",
    "006708200",
    "002609500",
    "800203009",
    "005010300"
]

# 转换为代码兼容的嵌套列表格式
board = str_to_board(input_sudoku)

3. 从文本文件读取输入的扩展方案

如果输入存储在txt文件中(每行一个9位数字串),可以用以下代码读取并转换:

def load_board_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    return str_to_board(lines)

# 调用示例
# board = load_board_from_file("sudoku_input.txt")

完整可运行修改后代码

def str_to_board(input_lines):
    return [[int(char) for char in line.strip()] for line in input_lines]

def solve(bo):
    find = find_empty(bo)
    if not find:
        return True
    else:
        row, col = find

    for i in range(1,10):
        if valid(bo, i, (row, col)):
            bo[row][col] = i

            if solve(bo):
                return True

            bo[row][col] = 0

    return False


def valid(bo, num, pos):
    # 检查行
    for i in range(len(bo[0])):
        if bo[pos[0]][i] == num and pos[1] != i:
            return False

    # 检查列
    for i in range(len(bo)):
        if bo[i][pos[1]] == num and pos[0] != i:
            return False

    # 检查3*3宫格
    box_x = pos[1] // 3
    box_y = pos[0] // 3

    for i in range(box_y*3, box_y*3 + 3):
        for j in range(box_x * 3, box_x*3 + 3):
            if bo[i][j] == num and (i,j) != pos:
                return False

    return True


def print_board(bo):
    for i in range(len(bo)):
        if i % 3 == 0 and i != 0:
            print("- - - - - - - - - - - - - ")

        for j in range(len(bo[0])):
            if j % 3 == 0 and j != 0:
                print(" | ", end="")

            if j == 8:
                print(bo[i][j])
            else:
                print(str(bo[i][j]) + " ", end="")


def find_empty(bo):
    for i in range(len(bo)):
        for j in range(len(bo[0])):
            if bo[i][j] == 0:
                return (i, j)  # 返回空白格行、列坐标

    return None

# 替换原有硬编码board为转换后的输入
input_sudoku = [
    "003020600",
    "900305000",
    "001806400",
    "008102900",
    "700000008",
    "006708200",
    "002609500",
    "800203009",
    "005010300"
]
board = str_to_board(input_sudoku)

print_board(board)
solve(board)
print("___________________")
print_board(board)

内容的提问来源于stack exchange,提问作者BjarnePW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:36:06