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.
判断一个9*9的方格是否可以组成一个数独;
我们只需要判断每行,每列,每个九宫格是否符合。
最主要推出check[board[3*(i/3) + j/3][3*(i%3) + j%3] - 48]
package leetcode;
public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
boolean ans = true;
if (board.length > 9 ) return false;
for (int i = 0; i<board.length; i++){
int[] lat = {0,0,0,0,0,0,0,0,0,0}; //横
int[] lon = {0,0,0,0,0,0,0,0,0,0}; //竖
int[] check = {0,0,0,0,0,0,0,0,0,0}; //方格 i - i%3 + j/3
if (board[i].length > 9) return false;
for (int j = 0; j<board[i].length; j++){
//if (board[i][j] == '.' || board[j][i] == '.' || board[3*(i/3) + j/3][3*(i%3) + j%3] == '.') continue;
//if (board[i][j] == '.') continue;
//System.out.println(board[3*(i/3) + j/3][3*(i%3) + j%3]);
//System.out.println(board[i][j]);
if ('1' <= board[i][j] && board[i][j] <= '9' ){
if (lat[board[i][j]-48] + 1 > 1){
return false;
}else{
lat[board[i][j]-48]++;
}
}
if ('1' <= board[j][i] && board[j][i] <= '9' ){
if (lon[board[j][i]-48] + 1 > 1){
return false;
}else{
lon[board[j][i]-48]++;
}
}
if ('1' <= board[3*(i/3) + j/3][3*(i%3) + j%3] && board[3*(i/3) + j/3][3*(i%3) + j%3] <= '9' ){
if (check[board[3*(i/3) + j/3][3*(i%3) + j%3] - 48] + 1 > 1){
return false;
}else{
check[board[3*(i/3) + j/3][3*(i%3) + j%3] - 48] ++;
}
}
}
}
return ans;
}
public static void main(String[] args){
//char[][] board = {"..4...63.",".........","5......9.","...56....","4.3.....1","...7.....","...5.....",".........","........."};
//System.out.println(new ValidSudoku().isValidSudoku(board));
}
}