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

Python实现9x9数独数组行、列、3x3子块去重校验(排除0值)

9×9数组重复值校验实现方案

需求说明

  • 校验对象:9×9二维数组
  • 排除规则:0为待填充值,不参与重复校验
  • 校验维度:行、列、拆分后的9个3×3子数组
  • 校验规则:1-9的数字在对应维度内不可重复

原代码问题

  1. 行列校验未过滤0值:直接对整行/列做去重比对,会将0纳入统计导致结果错误
  2. 3×3子数组校验逻辑错误:切片方式取的是左上角到指定坐标的区域,没有正确遍历所有9个3×3子数组,且不需要对子数组单独做行列校验,直接对整个子数组的非0值做去重校验即可

修正后可运行代码

import numpy as np

# 示例输入数组
test = np.array([
    [1, 0, 0, 7, 0, 0, 0, 0, 0],
    [0, 3, 2, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 6, 0, 0, 0, 0, 0],
    [0, 8, 0, 0, 0, 2, 0, 7, 0],
    [5, 0, 7, 0, 0, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 3, 6, 1, 0],
    [7, 0, 0, 0, 0, 0, 2, 0, 9],
    [0, 0, 0, 0, 5, 0, 0, 0, 0],
    [3, 0, 0, 0, 0, 4, 0, 0, 5]
])

def has_duplicate(arr):
    # 过滤所有0值
    non_zero = arr[arr != 0]
    # 去重后长度与原长度对比,不一致则存在重复
    return len(np.unique(non_zero)) != len(non_zero)

# 行校验
print("=== 行校验结果(存在重复返回True,无重复返回False) ===")
for r in range(9):
    print(f"第{r+1}行:{has_duplicate(test[r,:])}")

# 列校验
print("\n=== 列校验结果(存在重复返回True,无重复返回False) ===")
for c in range(9):
    print(f"第{c+1}列:{has_duplicate(test[:,c])}")

# 3x3子数组校验
print("\n=== 3x3子数组校验结果(存在重复返回True,无重复返回False) ===")
for r_block in range(3):
    for c_block in range(3):
        # 按块索引正确切片取出对应3x3区域
        block = test[r_block*3 : (r_block+1)*3, c_block*3 : (c_block+1)*3]
        print(f"第{r_block+1}行第{c_block+1}列子数组:{has_duplicate(block.flatten())}")

逻辑说明

  • 封装通用校验函数has_duplicate,统一处理0值过滤、重复判断逻辑,避免代码冗余
  • 3×3子数组通过块索引遍历,每次取对应坐标范围的切片,将子数组扁平化后再做重复校验,覆盖所有9个3×3区域
  • 输出结果中返回True代表当前维度存在1-9的重复值,返回False代表当前维度校验合法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:48:02