Determine 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 partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
題意分析:
本題是驗證一個數獨(不一定是完整的,空白的元素用"."來代替)是否是正確的。
先來看一下數獨的規則:
There are just 3 rules to Sudoku. |
|
Each row must have the numbers 1-9 occuring just once.
|
|
![]() |
|
Each column must have the numbers 1-9 occuring just once.
|
![]() |
And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid.
![]() |
很容易得到3個規則:
- 每一行只能出現1~9一次;
- 每一列只能出現1~9一次;
- 每個3×3子區域只能出現1~9一次(子區域之間沒有交叉,也就是一共有9個子區域)
解答:
本題直接根據數獨的規則“翻譯”成代碼就可以了:可以設3個長度為9的List,分別代表行、列、子區域。循環每個元素查看是否在相應的List中,如果存在說明重復,不符合規則;如果不存在就把當前元素加入到該List中。如果所有元素循環完畢,說明沒有重復值,返回True。該題可以假設輸入均合法,即都是1~9或"."。
AC代碼:
class Solution(object): def isValidSudoku(self, board): row = [[] for _ in xrange(9)] col = [[] for _ in xrange(9)] area = [[] for _ in xrange(9)] for i in xrange(9): for j in xrange(9): element = board[i][j] if element != '.': # calculate every sub-boxes, map to the left top element area_left_top_id = i / 3 * 3 + j / 3 if element in row[i] or element in col[j] or element in area[area_left_top_id]: return False else: row[i].append(element) col[j].append(element) area[area_left_top_id].append(element) return True