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

N皇后棋盘横向验证问题:Python代码错误排查与重构需求

N皇后验证问题修复与重构方案

问题定位

测试输入「59 24 41 19 52 13 30 47」对应8皇后问题(输入共8个位置,最大数59 < 8²=64),其中41和47的行号计算为 41 // 8 = 5、47 // 8 = 5,确实处于同一行。程序未检测到冲突,大概率是行判断逻辑错误(比如误用取模运算代替整数除法计算行号),或是未遍历所有皇后对进行冲突检查。

重构后完整代码

def print_chessboard(n):
    """打印编号为0到n²-1的n×n棋盘"""
    for row in range(n):
        row_numbers = [str(row * n + col).rjust(2) for col in range(n)]
        print(" ".join(row_numbers))

def is_queen_conflict(positions):
    """验证皇后位置是否存在互相攻击的情况"""
    n = len(positions)
    # 遍历所有皇后对(避免重复检查,只比较i<j的组合)
    for i in range(n):
        pos1 = positions[i]
        row1, col1 = pos1 // n, pos1 % n
        for j in range(i + 1, n):
            pos2 = positions[j]
            row2, col2 = pos2 // n, pos2 % n
            # 检查同行、同列、同对角线
            if row1 == row2 or col1 == col2 or abs(row1 - row2) == abs(col1 - col2):
                return True
    return False

if __name__ == "__main__":
    # 确定n(这里以8皇后为例,也可根据输入动态计算)
    n = 8
    print(f"{n}×{n}棋盘编号:")
    print_chessboard(n)
    
    # 获取用户输入
    input_str = input("请输入皇后位置(空格分隔):")
    positions = list(map(int, input_str.strip().split()))
    
    # 输入合法性校验
    if len(positions) != n or any(p < 0 or p >= n*n for p in positions):
        print("输入位置不合法")
    else:
        if is_queen_conflict(positions):
            print("FAIL")
        else:
            print("SUCCESS")

关键修复与重构点

  • 行号计算修正:用整数除法 pos // n 计算行号,取模 pos % n 计算列号,彻底解决同行判断错误的问题。
  • 全对遍历检查:采用双层循环遍历所有i<j的皇后对,确保每一对皇后的冲突都被检测到,避免遗漏。
  • 模块化拆分:将棋盘打印、冲突验证拆分为独立函数,代码结构更清晰,便于维护和扩展。
  • 输入合法性校验:新增输入检查,避免非法位置导致的逻辑错误。

测试验证

输入「59 24 41 19 52 13 30 47」时,程序会检测到41和47同行冲突,输出「FAIL」,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:55:42