leetcode36题 题解 翻译 C语言版 Python版
来源:互联网 发布:网络赌钱 编辑:程序博客网 时间:2024/06/05 21:18
36. Valid Sudoku
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.
36.有效数独
判断一个数独是不是有效的。参考:数独规则
数独的边界能被部分填充,空的地方填充字符'.'。
如图是一个部分填充的数独并且是有效的。
注意:
一个有效的数独不一定有解。只需要验证填充的地方就行了。
思路:按规则来逐行逐列逐九宫格判断是不是有重复数字就行了。每次判断时新建一个数组,每找到一个数先判断数组中是否有这个数,有的话就无效,没有就填进去。因为数是0-9的,所以可以建一个长度为10的数组采用计数的方式让数字对应下标,也可以图省事用ascii码对应数组下标。
bool isValidSudoku(char** board, int boardRowSize, int boardColSize) { for (int i = 0; i < boardRowSize; i++){ bool t[128] = {false}; for (int j = 0; j < boardColSize; j++){ if (board[i][j] == '.') continue; if (t[board[i][j]]) return false; else t[board[i][j]] = true; } } for (int j = 0; j < boardColSize; j++){ bool t[128] = {false}; for (int i = 0; i < boardRowSize; i++){ if (board[i][j] == '.') continue; if (t[board[i][j]]) return false; else t[board[i][j]] = true; } } for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ bool t[128] = {false}; for (int m = 0; m < boardRowSize / 3; m++){ for (int n = 0; n < boardColSize / 3; n++){ if (board[i*3+m][j*3+n] == '.') continue; if (t[board[i*3+m][j*3+n]]) return false; else t[board[i*3+m][j*3+n]] = true; } } } } return true;}
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ for line in board: for i, cell in enumerate(line): if cell != '.' and cell in line[:i]: return False board2 = zip(*board) for column in board2: for i, cell in enumerate(column): if cell != '.' and cell in column[:i]: return False for i in range(3): for j in range(3): num = [] for m in range(3): for n in range(3): cell = board[i*3+m][j*3+n] if cell != '.': if cell in num: return False else: num.append(cell) return True
0 0
- leetcode36题 题解 翻译 C语言版 Python版
- leetcode292题 题解 翻译 C语言版 Python版
- leetcode258题 题解 翻译 C语言版 Python版
- leetcode104题 题解 翻译 C语言版 Python版
- leetcode237题 题解 翻译 C语言版 Python版
- leetcode226题 题解 翻译 C语言版 Python版
- leetcode283题 题解 翻译 C语言版 Python版
- leetcode100题 题解 翻译 C语言版 Python版
- leetcode242题 题解 翻译 C语言版 Python版
- leetcode171题 题解 翻译 C语言版 Python版
- leetcode235题 题解 翻译 C语言版 Python版
- leetcode206题 题解 翻译 C语言版 Python版
- leetcode328题 题解 翻译 C语言版 Python版
- leetcode191题 题解 翻译 C语言版 Python版
- leetcode70题 题解 翻译 C语言版 Python版
- leetcode83题 题解 翻译 C语言版 Python版
- leetcode263题 题解 翻译 C语言版 Python版
- leetcode326题 题解 翻译 C语言版 Python版
- CSS定位
- iOS 处理图片的一些小 Tip
- C中一些运算符的使用
- 第七周 项目三
- Android——listview android:cacheColorHint,android:listSelector属性作用
- leetcode36题 题解 翻译 C语言版 Python版
- HDU 3001 Travelling
- iOS ----- MBProgressHUD、SVProgressHUD基本使用方法
- 关于postman使用的几点注意事项
- Mac下MySQL卸载方法
- 第八周实践项目1.2-数组作数据成员
- DP-BZOJ-1609-[Usaco2008 Feb]Eating Together麻烦的聚餐
- 用对象数组操作长方柱类
- 关于Java各种流的一点笔记