九宫格验证,验证这个数独游戏的棋盘是否合法,这题做的不是求解答案,只是看给定的棋盘是否合法!
做法没什么特别的,分块,行,列都要验证,即一个分组单位里1-9有且只能出现一次
注意空间优化
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.
public class Solution {
static int position[]=new int[]{2,4,8,16,32,64,128,256,512};
/** * 分别判断行 列 和 格子内的就可以了~~~ * 这里我使用的位运算来降低内存。。都是2的n次,那么对应的位置上直接使用位运算就能判断了 * */
public boolean isValidSudoku(char[][] board) {
int col[]=new int[9];
int row[]=new int[9];
int zone[]=new int[9];
int i,j,mask,qid;
for(i=0;i<9;i++){
for(j=0;j<9;j++){
if(board[i][j]=='.')
continue;
mask=position[board[i][j]-'1'];
qid=(i/3)*3+j/3;
if( (col[j] | mask) == col[j] || (row[i] | mask) == row[i] ||(zone[qid] | mask) == zone[qid])
return false;
col[j]=col[j]|mask;
row[i]=row[i]|mask;
zone[qid]=zone[qid]|mask;
}
}
return true;
}
}