[LeetCode]题解(python):036-Valid Sudoku


题目来源

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)


 1 _author_ = "YE"
 2 # -*- coding:utf-8 -*-
 3 class Solution(object):
 4     def verifyRow(self, board):
 5         for i in range(9):
 6             L = []
 7             for j in range(9):
 8                 if board[i][j] == '.':
 9                     continue
10                 elif board[i][j] in L:
11                     return False
12                 else:
13                     L.append(board[i][j])
14         return True
15 
16     def verifyColumn(self, board):
17         for j in range(9):
18             L = []
19             for i in range(9):
20                 if board[i][j] == '.':
21                     continue
22                 elif board[i][j] in L:
23                     return False
24                 else:
25                     L.append(board[i][j])
26         return True
27 
28     def verifySquare(self, board):
29         for i in range(3):
30             for j in range(3):
31                 L = []
32                 for k in range(3):
33                     for x in range(3):
34                         if board[3 * i + k][3 * j + x] == '.':
35                             continue
36                         elif board[3 * i + k][3 * j + x] in L:
37                             return False
38                         else:
39                             L.append(board[3 * i + k][3 * j + x])
40         return True
41 
42     def isValidSudoku(self, board):
43         """
44         :type board: List[List[str]]
45         :rtype: bool
46         """
47         numbers = len(board[0])
48         print(numbers)
49 
50         # print('row:',self.verifyRow(board))
51         if not self.verifyRow(board):
52             return False
53         # print('column:',self.verifyColumn(board))
54         if not self.verifyColumn(board):
55             return False
56         # print('square:',self.verifySquare(board))
57         if not self.verifySquare(board):
58             return False
59 
60         return True
61 
62 #test code
63 s = Solution()
64 board = [".87654321","2........","3........","4........","5........","6........","7........","8........","9........"]
65 print(s.isValidSudoku(board))
原文地址:https://www.cnblogs.com/loadofleaf/p/5010566.html