Leetcode||36. Valid Sudoku
来源:互联网 发布:iss端口和wamp端口 编辑:程序博客网 时间:2024/05/22 12:54
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.
数独的规则:数独的每一行、每一列、9个九宫格里的数字只能是0-9,且不能重复。
经典一点,就暴力破解,三个规则都过一遍
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ for i in range(9): if not self.isValidNine(board[i]): return False col = [c[i] for c in board] if not self.isValidNine(col): return False for i in [0, 3, 6]: for j in [0, 3, 6]: block = [board[s][t] for s in [i, i+1, i+2] for t in [j, j+1, j+2]] if not self.isValidNine(block): return False return True def isValidNine(self, row): map = {} for c in row: if c != '.': if c in map: return False else: map[c] = True return True
网上找了一个非常短小的代码,值得学习,方法是记录所有出现过的行、列、块的数字及相应位置,最后判断是否有重复,用set操作精简代码
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ seen = [] for i, row in enumerate(board): for j, col in enumerate(row): if col != '.': seen += [(col, j), (i, col), (i/3, j/3, col)] return len(seen) == len(set(seen))
阅读全文
0 0
- [LeetCode]36.Valid Sudoku
- LeetCode --- 36. Valid Sudoku
- LeetCode 36.Valid Sudoku
- [Leetcode] 36. Valid Sudoku
- 【leetcode】36. Valid Sudoku
- [leetcode] 36. Valid Sudoku
- Leetcode 36. Valid Sudoku
- 36. Valid Sudoku LeetCode
- leetcode 36. Valid Sudoku
- LeetCode *** 36. Valid Sudoku
- leetcode 36. Valid Sudoku
- [LeetCode]36. Valid Sudoku
- LeetCode 36. Valid Sudoku
- leetcode-36. Valid Sudoku
- 36.[Leetcode]Valid Sudoku
- Leetcode 36.Valid Sudoku
- LeetCode-36.Valid Sudoku
- leetcode 36. Valid Sudoku
- CentOS 7下安装Redis 4
- Android Render(一)Activity窗口构成和绘制解析
- 云原生(Cloud Native)- 移动App研发新范式
- ubuntu 解决非正常关闭apt-get的锁
- 将 Intent 序列化,像 Uri 一样传递 Intent!!!
- Leetcode||36. Valid Sudoku
- HTML
- Java并发编程实战--笔记三
- BOM中的窗口弹出和关闭
- @Html.DropDownList
- iframe和frame的区别
- spring boot学习(二)---配置文件的注入
- java中Date类型的比较方法
- 通过JS和CSS,实现网页加载中的动画效果