题解 | #Sudoku#

Sudoku

https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1

table = []
for _ in range(9):
    table.append(input().split())


def isvalid(r, c, num) -> bool:
    for i in range(9):
        if table[r][i] == str(num) or table[i][c] == str(num):
            return False

    for i in range(3):
        for j in range(3):
            if table[r // 3 * 3 + i][c // 3 * 3 + j] == str(num):
                return False
    return True


def solved() -> bool:
    for r in range(9):
        for c in range(9):
            if table[r][c] == "0":
                for num in range(1, 10):
                    if isvalid(r, c, num):
                        table[r][c] = str(num)
                        if solved():
                            return True
                        table[r][c] = "0"
                return False
    return True


solved()
for row in table:
    print(" ".join(row))

全部评论

相关推荐

完美的潜伏者许愿简历通过:我上表jd,请求封我做后端大将军的事,北京有消息了:竟然不许!!! 他们一定是看我没有实习,这才故意驳回我的请求!
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务