Python中的有效数独
假设我们有一个9x9 Sudoku板。我们必须检查它是否有效或现在。仅需根据以下规则验证填充的单元格-
每行必须包含1-9之间的数字,且不能重复。
每列必须包含1-9之间的数字,且不能重复。
网格的9个(3x3)子框中的每个必须包含1-9之间的数字,且不能重复。
假设数独网格就像-
5 | 3 | 7 | ||||||
6 | 1 | 9 | 5 | |||||
9 | 8 | 6 | ||||||
8 | 6 | 3 | ||||||
4 | 8 | 3 | 1 | |||||
7 | 2 | 6 | ||||||
6 | 2 | 8 | ||||||
4 | 1 | 9 | 5 | |||||
8 | 7 | 9 |
这是有效的。
为了解决这个问题,我们将遵循以下步骤-
当我在0到8的范围内
如果board [i,j]不为空,并且board [i,j]为行,则返回false
row [board [i,j]]:= 1
如果board [j,i]不为空,而board [j,i]为col,则返回false
col [board [j,i]]:= 1
rc:= row_cube + j / 3和cc:= col_cube + j mod 3
如果块中的board [rc,cc]和board [rc,cc]不为空,则返回false
块[board [rc,cc]]:= 1
创建一些空字典,分别称为row,col和block,row_cube:= 3 *(i / 3)和col_cube:= 3 *(i mod 3)
对于j在0到8的范围内
返回真
示例(Python)
让我们看下面的实现以更好地理解-
class Solution(object):def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(9):
row = {}
column = {}
block = {}
row_cube = 3 * (i//3)
column_cube = 3 * (i%3)
for j in range(9):
if board[i][j]!='.' and board[i][j] in row:
return False
row[board[i][j]] = 1
if board[j][i]!='.' and board[j][i] in column:
return False
column[board[j][i]] = 1
rc= row_cube+j//3
cc = column_cube + j%3
if board[rc][cc] in block and board[rc][cc]!='.':
return False
block[board[rc][cc]]=1
return True
ob1 = Solution()print(ob1.isValidSudoku([
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]]))
输入值
[["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
输出结果
true
以上是 Python中的有效数独 的全部内容, 来源链接: utcz.com/z/354316.html