题解 | #Sudoku#

Sudoku

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

import sys

matrix = [[0]*9 for _ in range(9)]
for i in range(9):
    matrix[i] = sys.stdin.readline().strip().split()

def backtracking(matrix):
    for i in range(9):
        for j in range(9):
            if matrix[i][j] == '0':
                for value in range(1,10):
                    if isValid(matrix, i, j, str(value)):
                        matrix[i][j] = str(value)
                        if backtracking(matrix): 
                            return True
                    matrix[i][j] = '0'
                return False   # 如果九个数都试过,没有找到,就返回False
    return True     # 遍历完没有返回False,说明找到了合适的棋盘


def isValid(m, x, y, value):
    for j in range(9):   # 检查同一行有没有value
        if m[x][j] == value:
            return False
    for i in range(9):
        if m[i][y] == value:   # 检查同一列
            return False
    
	xboard = x//3
    yboard = y//3
	for i in range(xboard*3, (xboard+1)*3):   # 检查同一九宫格
        for j in range(yboard*3, (yboard+1)*3):
            if i != x and j !=y and m[i][j] == value:
                return False
    return True


backtracking(matrix)
for i in range(9):
    matrix[i] = list(map(str, matrix[i]))
    print(' '.join(matrix[i]))



全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务