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.
public class Solution {
public boolean isValidSudoku(char[][] board) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
//判断每行是否有相同元素出现
for(int i=0;i<9;i++){
for(int m=0;m<9;m++){
map.put((char)('1'+m),0);
}
for(int j=0;j<9;j++){
if('1'<=board[i][j]&&board[i][j]<='9'){
int value = map.get(board[i][j])+1;
map.put(board[i][j], value);
if(map.get(board[i][j])>1){
return false;
}
}
}
}
//判断每列是否有相同元素出现
for(int i=0;i<9;i++){
for(int m=0;m<9;m++){
map.put((char)('1'+m),0);
}
for(int j=0;j<9;j++){
if('1'<=board[j][i]&&board[j][i]<='9'){
int value = map.get(board[j][i])+1;
map.put(board[j][i], value);
if(map.get(board[j][i])>1){
return false;
}
}
}
}
//判断每一个子格里(sub-boxes of the grid)是否有相同元素
for(int i=0;i<9;i=i+3){
for(int j=0;j<9;j=j+3){
for(int m=0;m<9;m++){
map.put((char)('1'+m),0);
}
for(int k=0;k<3;k++){
for(int x=0;x<3;x++){
if('1'<=board[i+k][j+x]&&board[i+k][j+x]<='9'){
int value = map.get(board[i+k][j+x])+1;
map.put(board[i+k][j+x], value);
if(map.get(board[i+k][j+x])>1){
return false;
}
}
}
}
}
}
return true;
}
}
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.

本文介绍了一种通过编程方法验证数独盘面是否符合数独基本规则的方法。该方法不仅检查每一行和每一列,还检查每个3x3的小宫格内数字是否重复。即使数独未被完全填满,也能确保所有已填充的数字遵循数独的基本规则。

838

被折叠的 条评论
为什么被折叠?



