题目来源:
https://leetcode.com/problems/valid-sudoku/
题意分析:
判断一个数独是不是可以满足规则的,也就是列行和小九宫格都是包括有且仅有1到9.
题目思路:
刚开始看这个题目的时候觉得就是要先把数独给填好,可以填好就是true的,否者就是false。不过这只是一个easy难度的题目,不可能要这么做吧。然后我测试了一些数据,发现[".87654321","2........","3........","4........","5........","6........","7........","8........","9........"]这个竟然是true。因为如果要玩,那么第一个数填1和9都是错的,所以他应该是不满足的,应该false,但是他的答案是true的。
所以,题目应该要判断的是当前的状态是不是满足规则的。所以值需要将所有的行列小九宫判断一下就行了。
代码(python):
1 class Solution(object): 2 def isValidSudoku(self, board): 3 """ 4 :type board: List[List[str]] 5 :rtype: bool 6 """ 7 #列判断 8 i = 0 9 while i < 9: 10 j = 0 11 d = {} 12 while j < 9: 13 if board[i][j] != ‘.‘ and board[i][j] in d: 14 return False 15 else: 16 d[board[i][j]] = True 17 j += 1 18 i += 1 19 #行判断 20 j = 0 21 while j < 9: 22 i = 0 23 d = {} 24 while i < 9: 25 if board[i][j] != ‘.‘ and board[i][j] in d: 26 return False 27 else: 28 d[board[i][j]] = True 29 i += 1 30 j += 1 31 #九宫格 32 i = 0 33 while i < 9: 34 j = 0 35 while j < 9: 36 m = 0;d = {} 37 while m < 3: 38 n = 0 39 while n < 3: 40 if board[i + m][j + n] != ‘.‘ and board[i + m][j + n] in d: 41 return False 42 else: 43 d[board[i + m][j + n]] = True 44 n += 1 45 m += 1 46 j += 3 47 i += 3 48 return True
转载请注明出处:http://www.cnblogs.com/chruny/p/4926247.html
时间: 2024-10-09 12:32:21