本文主要是介绍leetcode36~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.
对于检验的规则可访问链接:
http://sudoku.com.au/TheRules.aspx
分别对 行 列 和小的九宫格进行校验即可。
关键在对小九宫格进行校验时范围的选取
public class ValidSudoku {//set集合用于存放元素值,进行重复性检查public boolean isValidSudoku2(char[][] board) {Set<Character> set = new HashSet<Character>();//按行检验for(int i=0;i<9;i++) {for(int j=0;j<9;j++) {if(board[i][j]>='1' && board[i][j]<='9') {if(!set.add(board[i][j])) {return false;}}}set.clear();}//按列检验for(int i=0;i<9;i++) {for(int j=0;j<9;j++) {if(board[j][i]>='1' && board[j][i]<='9') {if(!set.add(board[j][i])) {return false;}}}set.clear();}//按小的九宫格检验for(int i=0;i<9;i+=3) {for(int j=0;j<9;j+=3) {for(int row=i;row<i+3;row++) {for(int column=j;column<j+3;column++) {if(board[row][column]>='1' && board[row][column]<='9') {if(!set.add(board[row][column])) {return false;}}}}set.clear();}}return true;}public boolean isValidSudoku(char[][] board) {Set<Character> rows = new HashSet<>();Set<Character> columns = new HashSet<>();Set<Character> cubes = new HashSet<>();for(int i=0;i<9;i++) {rows.clear();columns.clear();cubes.clear();for(int j=0;j<9;j++) {//行检查if(board[i][j]!='.' && !rows.add(board[i][j])) {return false;}//列检查if(board[j][i]!='.' && !columns.add(board[j][i])) {return false;}//小的九宫格检查int r = (i/3)*3;int c = (i%3)*3;if(board[r+j/3][c+j%3]!='.' && !cubes.add(board[r+j/3][c+j%3])) {return false;}}}return true;}
}
这篇关于leetcode36~Valid Sudoku的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!