题解 | #Sudoku#
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
# 菜鸡参考大神代码写的,马一下 import sys sudoku = [] nums = set(range(1, 10)) for line in sys.stdin: sudoku.append(list(map(int, line.strip().split()))) def sub_matrix(p): """calculate the start location of a 3X3 matrix which contain p""" x, y = p boder = [0, 3, 6] if x not in boder: if 0 <= x <= 2: x = 0 elif 3 <= x <= 5: x = 3 else: x = 6 if y not in boder: if 0 <= y <= 2: y = 0 elif 3 <= y <= 5: y = 3 else: y = 6 return [x, y] def check_sudoku_properties(sudoku, i, j, num): line_x, line_y, start, matrix = sudoku[i], [], sub_matrix([i, j]), [] for line in sudoku: line_y.append(line[j]) m, n = start for line in sudoku[m:m+3]: matrix.extend(line[n:n+3]) if num in line_x or num in line_y or num in matrix: return False else: return True def dfs(sudoku): for i in range(9): for j in range(9): if sudoku[i][j] == 0: for num in nums: # print(num, i, j) check = check_sudoku_properties(sudoku, i, j, num) # print(check) if check: sudoku[i][j] = num # print(num, i, j) res = dfs(sudoku) if res: return True sudoku[i][j] = 0 return False return True dfs(sudoku) for line in sudoku: print(*line, sep=' ')