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.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
思路:题目非常easy。主要是规则的理解,数独的游戏没有玩过。不知道什么规则,我以为随意9个方格1-9的个数都至多为1,谁知规则是特定的九个格内1-9的个数至多为1。其它不考虑。
代码比較啰嗦,但思路清晰,例如以下:
public class Solution {
//置为静态变量
static Map<Character,Integer> map = new HashMap<Character,Integer>();
public boolean isValidSudoku(char[][] board) {
//推断每行
for(int i = 0; i < board.length; i++){
initMap();//每次均需初始化
for(int j = 0; j < board[0].length; j++){
//是数字
if(board[i][j] >= '0' && board[i][j] <= '9'){
if(map.get(board[i][j]) > 0){//说明反复数字
return false;
}else{
map.put(board[i][j],1);
}
}else if(board[i][j] != '.'){//出现空格和0-9之外的字符
return false;//直接返回false
}
}
}
//推断每列
for(int i = 0; i < board[0].length; i++){
initMap();//每次均需初始化
for(int j = 0; j < board.length; j++){
//是数字
if(board[j][i] >= '0' && board[j][i] <= '9'){
if(map.get(board[j][i]) > 0){//说明反复数字
return false;
}else{
map.put(board[j][i],1);
}
}else if(board[j][i] != '.'){//出现空格和0-9之外的字符
return false;//直接返回false
}
}
}
//推断九宫格
for(int i = 0; i < board.length - 2; i = i+3){//行{
for(int j = 0; j < board[0].length - 2; j=j+3){
initMap();//初始化
for(int m = i; m < i + 3;m++){
for(int n = j; n < j+3; n++){
//是数字
if(board[m][n] >= '0' && board[m][n] <= '9'){
if(map.get(board[m][n]) > 0){//说明反复数字
return false;
}else{
map.put(board[m][n],1);
}
}else if(board[m][n] != '.'){//出现空格和0-9之外的字符
return false;//直接返回false
}
}
}
}
}
return true;
}
//初始化map为每一个key均赋值0
private void initMap(){
for(char i = '0';i <= '9'; i++){
map.put(i,0);
}
}
}