classSolution{//拿boolean[][] rows来举例//row标识对应的行,col标识出现的数字,value标识是否出现privatefinalint L =9;publicbooleanisValidSudoku(char[][] board){boolean[][] rows =newboolean[L][L];boolean[][] cols =newboolean[L][L];boolean[][] boxes =newboolean[L][L];for(int r =0; r < L;++r){for(int c =0; c < L;++c){if(board[r][c]!='.'){int value = board[r][c]-'1';int boxIndex = r /3*3+ c /3;if(rows[r][value]|| cols[c][value]|| boxes[boxIndex][value]){returnfalse;}//记录每一行中的数字,r是行数,value是元素值
rows[r][value]=true;//记录每一列中的数字,c是行数,value是元素值
cols[c][value]=true;//记录每一块元素中的数字,r / 3 * 3 + c / 3得到的是每一块区域对应的坐标值,value是元素值
boxes[boxIndex][value]=true;}}}returntrue;}}
2、解数独
classSolution{publicvoidsolveSudoku(char[][] board){// 三个布尔数组 表明 行, 列, 还有 3*3 的方格的数字是否被使用过boolean[][] rowUsed =newboolean[9][10];boolean[][] colUsed =newboolean[9][10];boolean[][][] boxUsed =newboolean[3][3][10];// 初始化for(int row =0; row < board.length; row++){for(int col =0; col < board[0].length; col++){int num = board[row][col]-'0';if(1<= num && num <=9){
rowUsed[row][num]=true;
colUsed[col][num]=true;
boxUsed[row/3][col/3][num]=true;}}}// 递归尝试填充数组 recusiveSolveSudoku(board, rowUsed, colUsed, boxUsed,0,0);}privatebooleanrecusiveSolveSudoku(char[][]board,boolean[][]rowUsed,boolean[][]colUsed,boolean[][][]boxUsed,int row,int col){// 边界校验, 如果已经填充完成, 返回true, 表示一切结束if(col == board[0].length){
col =0;
row++;if(row == board.length){returntrue;}}// 是空则尝试填充, 否则跳过继续尝试填充下一个位置if(board[row][col]=='.'){// 尝试填充1~9for(int num =1; num <=9; num++){boolean canUsed =!(rowUsed[row][num]|| colUsed[col][num]|| boxUsed[row/3][col/3][num]);if(canUsed){
rowUsed[row][num]=true;
colUsed[col][num]=true;
boxUsed[row/3][col/3][num]=true;
board[row][col]=(char)('0'+ num);if(recusiveSolveSudoku(board, rowUsed, colUsed, boxUsed, row, col +1)){returntrue;}
board[row][col]='.';
rowUsed[row][num]=false;
colUsed[col][num]=false;
boxUsed[row/3][col/3][num]=false;}}}else{returnrecusiveSolveSudoku(board, rowUsed, colUsed, boxUsed, row, col +1);}returnfalse;}}
1、有效的数独class Solution { //拿boolean[][] rows来举例 //row标识对应的行,col标识出现的数字,value标识是否出现 private final int L = 9; public boolean isValidSudoku(char[][] board) { boolean[][] rows = new boolean[L][L]; boolean[][] cols = new boolean