LeetCode Valid Sudoku
来源:互联网 发布:mysql 1054 编辑:程序博客网 时间:2024/06/06 07:35
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.
题意:给出一个数独块,已经填了数据,问根据已填的数据判断数独是不是合法的。
思路:在扫描时,如果当前单元格已经填了数, 就判断当前行、当前列、所在的小矩形块的已填的数是不是有重复。如果有重复,说明是不合法的。
代码如下:
class Solution{ public boolean isValidSudoku(char[][] board) { int n = board.length; Set<Integer> hs = new HashSet<Integer>(); int m = (int)Math.floor(Math.sqrt(n)); for (int i = 1; i <= n; i++) { hs.add(i); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] != '.') { Set<Integer> tmp = new HashSet<Integer>(hs); for (int k = 0; k < n; k++) { if (board[i][k] == '.') continue; int num = board[i][k] - '0'; if (!tmp.contains(num)) return false; tmp.remove(num); } tmp = new HashSet<Integer>(hs); for (int k = 0; k < n; k++) { if (board[k][j] == '.') continue; int num = board[k][j] - '0'; if (!tmp.contains(num)) return false; tmp.remove(num); } tmp = new HashSet<Integer>(hs); int row = i / m, col = j / m; for (int a = row * m; a < (row + 1) * m; a++) { for (int b = col * m; b < (col + 1) * m; b++) { if (board[a][b] == '.') continue; int num = board[a][b] - '0'; if (!tmp.contains(num)) return false; tmp.remove(num); } } } } } return true; }}
0 0
- 【LeetCode】Valid Sudoku && Sudoku Solver
- [Leetcode]Sudoku Solver&&Valid Sudoku
- leetcode Valid Sudoku & Sudoku Solver
- LeetCode : Valid Sudoku
- [LeetCode]Valid Sudoku
- [leetcode] Valid Sudoku
- LeetCode-Valid Sudoku
- LeetCode Valid Sudoku
- LeetCode - Valid Sudoku
- LeetCode:Valid Sudoku
- leetcode-036:Valid Sudoku
- Leetcode: Valid Sudoku
- LeetCode题解:Valid Sudoku
- 【LeetCode】 Valid Sudoku
- Leetcode Valid Sudoku
- LeetCode | Valid Sudoku
- LeetCode Valid Sudoku
- [Leetcode] Valid Sudoku (Java)
- 1025: [SCOI2009]游戏 线性筛素数+DP
- 1046. Shortest Distance (20)
- Shiro简介
- Visual Studio 2008 可扩展性开发(四):添加新的命令
- lighttpd-1.4.39 : fdevents and Event Handler
- LeetCode Valid Sudoku
- oracle数据库学习(二)
- sklearn sparse matrix 的构造方法
- HDOJ 1005 Number Sequence
- 解决“Git Windows客户端保存用户名与密码”的问题
- DLL的使用
- java概述
- MIPS构架简介
- c#正则表达式详解