码迷,mamicode.com
首页 > 其他好文 > 详细

36. Valid Sudoku 有效的数独

时间:2018-01-20 00:20:28      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:eterm   ble   ali   type   lin   return   lang   png   str   

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. 


验证当前九宫格盘面是否有错误

  1. class Solution:
  2. def valid3by3(self, board, row, col):
  3. validPos = [
  4. [-1, -1], [-1, 0], [-1, 1],
  5. [0, -1], [0, 0], [0, 1],
  6. [1, -1], [1, 0], [1, 1]
  7. ]
  8. s = set()
  9. for pos in validPos:
  10. curVal = board[row + pos[0]][col + pos[1]]
  11. if curVal is ".":
  12. continue
  13. if curVal in s:
  14. return False
  15. s.add(curVal)
  16. return True
  17. def validRow(self, board, row):
  18. s = set()
  19. for curVal in board[row]:
  20. if curVal is ".":
  21. continue
  22. if curVal in s:
  23. return False
  24. s.add(curVal)
  25. return True
  26. def validCol(self, board, col):
  27. s = set()
  28. for row in board:
  29. curVal = row[col]
  30. if curVal is ".":
  31. continue
  32. if curVal in s:
  33. return False
  34. s.add(curVal)
  35. return True
  36. def isValidSudoku(self, board):
  37. """
  38. :type board: List[List[str]]
  39. :rtype: bool
  40. """
  41. pos3by3 = [
  42. [1, 1], [1, 4], [1, 7],
  43. [4, 1], [4, 4], [4, 7],
  44. [7, 1], [7, 4], [7, 7]
  45. ]
  46. for pos in pos3by3:
  47. if not self.valid3by3(board, pos[0], pos[1]):
  48. return False
  49. for row in range(0, 9):
  50. if not self.validRow(board, row):
  51. return False
  52. for col in range(0, 9):
  53. if not self.validCol(board, col):
  54. return False
  55. return True
  56. s = Solution()
  57. board = [
  58. [".", "8", "7", "6", "5", "4", "3", "2", "1"],
  59. ["2", ".", ".", ".", ".", ".", ".", ".", "."],
  60. ["3", ".", ".", ".", ".", ".", ".", ".", "."],
  61. ["4", ".", ".", ".", ".", ".", ".", ".", "."],
  62. ["5", ".", ".", ".", ".", ".", ".", ".", "."],
  63. ["6", ".", ".", ".", ".", ".", ".", ".", "."],
  64. ["7", ".", ".", ".", ".", ".", ".", ".", "."],
  65. ["8", ".", ".", ".", ".", ".", ".", ".", "."],
  66. ["9", ".", ".", ".", ".", ".", ".", ".", "."]
  67. ]
  68. res = s.isValidSudoku(board)
  69. print(res)








36. Valid Sudoku 有效的数独

标签:eterm   ble   ali   type   lin   return   lang   png   str   

原文地址:https://www.cnblogs.com/xiejunzhao/p/8319163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!