看了两种方法:
1.官方:作者:LeetCode
链接:https://leetcode-cn.com/problems/valid-sudoku/solution/you-xiao-de-shu-du-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2.作者:liujin-4
链接:https://leetcode-cn.com/problems/valid-sudoku/solution/36-jiu-an-zhao-cong-zuo-wang-you-cong-shang-wang-x/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
个人微改:
一:
import java.util.HashMap;
public class effectiveSudoku {
public static void main(String args[]) {
char a[][] = new char[][] {
{'5','3','.','.','7','.','.','.','.'}
,{'6','.','.','1','9','5','.','.','.'}
,{'.','9','8','.','.','.','.','6','.'}
,{'8','.','.','.','6','.','.','.','3'}
,{'4','.','.','8','.','3','.','.','1'}
,{'7','.','.','.','2','.','.','.','6'}
,{'.','6','.','.','.','.','2','8','.'}
,{'.','.','.','4','1','9','.','.','5'}
,{'.','.','.','.','8','.','.','7','9'}};
boolean b = valid(a);
System.out.println(b);
}
static boolean valid(char[][] board) {
HashMap<Integer,Integer> rows[] = new HashMap[9];
HashMap<Integer,Integer> columns[] = new HashMap[9];
HashMap<Integer,Integer> boxes[] = new HashMap[9];
for(int i=0;i<9;i++) {
rows[i] = new HashMap<Integer,Integer>();
columns[i] = new HashMap<Integer,Integer>();
boxes[i] = new HashMap<Integer,Integer>();
}
for(int i=0;i<9;i++) {
for(int j=0;j<9;j++) {
char num = board[i][j];
if(num!='.') {
int n = (int)num;
int box_index = (i/3)*3+j/3;
rows[i].put(n,rows[i].getOrDefault(n,0)+1);
columns[j].put(n,columns[j].getOrDefault(n,0)+1);
boxes[box_index].put(n,boxes[box_index].getOrDefault(n,0)+1);
if(rows[i].get(n)>1||columns[j].get(n)>1||boxes[box_index].get(n)>1) {
return false;
}
}
}
}
return true;
}
}
二:
public class effectiveSudoku_2 {
public static void main(String args[]) {
char a[][] = new char[][] {
{'5','3','.','.','7','.','.','.','.'}
,{'6','.','.','1','9','5','.','.','.'}
,{'.','9','8','.','.','.','.','6','.'}
,{'8','.','.','.','6','.','.','.','3'}
,{'4','.','.','8','.','3','.','.','1'}
,{'7','.','.','.','2','.','.','.','6'}
,{'.','6','.','.','.','.','2','8','.'}
,{'.','.','.','4','1','9','.','.','5'}
,{'.','.','.','.','8','.','.','7','9'}};
boolean b = valid(a);
System.out.println(b);
}
static boolean valid(char[][] board) {
int [][]row = new int[9][10];
int [][]column = new int[9][10];
int [][]box = new int[9][10];
for(int i=0;i<9;i++) {
for(int j=0;j<9;j++) {
if(board[i][j]=='.') {
continue;
}
int curNum = board[i][j]-'0';
if(row[i][curNum]==1) {
return false;
}
if(column[j][curNum]==1) {
return false;
}
if (box[j/3 + (i/3) * 3][curNum]==1){
return false;
}
row[i][curNum]=1;
column[j][curNum]=1;
box[j/3 + (i/3) * 3][curNum]=1;
}
}
return true;
}
}

本文对比了使用哈希表和二维数组实现的两种有效数独验证算法,展示了如何检查行、列和宫格内数字的唯一性,以确保数独的正确性。
4782

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



