Leetcode - Valid Sudoku
2016-04-10 15:13
316 查看
Question
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 ‘.’.
简述一下检查的规则:
1. 每一行中数字1~9只能出现一次;
2. 每一列中数字1~9只能出现一次;
3. 9个子格子中数字1~9只能出现一次;
Note
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.Java Code
public boolean isValidSudoku(char[][] board) { //检查所有行 for(int i = 0; i < 9; ++i) { if(check(board[i])) return false; } char[] temp = new char[9];//存放当前需要检查的字符 //检查所有列 for(int i = 0; i < 9; ++i) { for(int j = 0; j < 9; ++j) temp[j] = board[j][i]; if(check(temp)) return false; } //检查所有sub-boxes for(int xStep = 0; xStep < 9; xStep += 3) { for(int yStep = 0; yStep < 9; yStep += 3) { for(int i = 0; i < 3; ++i) for(int j = 0; j < 3; ++j) temp[j + 3*i] = board[i + xStep][j + yStep]; if(check(temp)) return false; } } //检查都通过,则是有效的数独 return true; } //检查当前区域是否有重复数字,有重复则返回true //版本一:直接两两字符之间比较 public boolean check(char[] str) { int j; char c; for(int i=0; i<str.length - 1; ++i) { c = str[i]; if(c == '.') continue; for(j = i + 1;j<str.length;++j){ if(c == str[j]) return true; } } return false; } //版本二: 使用HashSet public boolean check(char[] str, boolean b) { HashSet<String> hs = new HashSet<>(); for(int i = 0; i < 9; ++i) { if (str[i] == '.') continue; if(!hs.add(str[i]+"")) return true; } return false; }
说明
本题没有太多的技巧性可言,主要是取出9个子格子的过程要注意二维数组的索引变化规律,另外检查temp字符数组是否有重复字符的方式有多种,由于temp数组只有9个元素,所以这里直接比较比用Set处理更加高效相关文章推荐
- Firefox下提示illegal character并出现乱码的原因
- Python UnicodeEncodeError: 'gbk' codec can't encode character 解决方法
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- GP数据库笔记--数据类型转换,杀掉进程的方法
- GP数据库关于行列转换
- GP数据库笔记—表结构查询,表占用空间查询
- apache日志分析
- C语言回顾与再学习——setbuf
- 数据类型转换
- 查看修改mysql编码方式
- Linux上删除空行的方法
- C语言 isdigit
- Python错误: SyntaxError: Non-ASCII character eclipse pydev 下
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number