题目来源
https://leetcode.com/problems/valid-sudoku/
etermine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
. A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
题意分析
Input: a list means the sudoku with each element in the list is a str
Output:True or False
Conditions:看已有的数字是否满足数独的条件(每行、列、小九方格不能一样的数字)
题目思路
此题是判断已有的矩阵块是否为有效的数独组,分别遍历每一行,每一列,每一个小九方格即可,注意下标范围
AC代码(Python)
_author_ = "YE"
# -*- coding:utf-8 -*-
class Solution(object):
def verifyRow(self, board):
for i in range(9):
L = []
for j in range(9):
if board[i][j] == '.':
continue
elif board[i][j] in L:
return False
else:
L.append(board[i][j])
return True def verifyColumn(self, board):
for j in range(9):
L = []
for i in range(9):
if board[i][j] == '.':
continue
elif board[i][j] in L:
return False
else:
L.append(board[i][j])
return True def verifySquare(self, board):
for i in range(3):
for j in range(3):
L = []
for k in range(3):
for x in range(3):
if board[3 * i + k][3 * j + x] == '.':
continue
elif board[3 * i + k][3 * j + x] in L:
return False
else:
L.append(board[3 * i + k][3 * j + x])
return True def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
numbers = len(board[0])
print(numbers) # print('row:',self.verifyRow(board))
if not self.verifyRow(board):
return False
# print('column:',self.verifyColumn(board))
if not self.verifyColumn(board):
return False
# print('square:',self.verifySquare(board))
if not self.verifySquare(board):
return False return True #test code
s = Solution()
board = [".87654321","2........","3........","4........","5........","6........","7........","8........","9........"]
print(s.isValidSudoku(board))