题意:数独游戏,9*9的方格中,要求每一行、每一列、每个3*3的小矩阵都没有重复的数字。
思路:可以利用hashset的唯一性来求得。对每一行、每一列、每个3*3矩阵(共9个)进行遍历,看是否有重复的数字。
代码:
package ValidSudo;
import java.util.HashSet;
public class ValidSudo {
//利用hashset的唯一性来求解
public boolean FindValidSuso(char[][] board){
HashSet< Character> hs = new HashSet<>();
//检查每行
for (int i = 0 ; i< 9 ;i++){
for(int j = 0 ; j < 9 ; j++){
if(board[i][j] == '.')
continue;
if (hs.contains(board[i][j]))
return false;
hs.add(board[i][j]);
}
hs.clear();
}
//检查每列
for (int j = 0 ; j< 9 ; j++){
for(int i = 0 ; i < 9 ; i++){
if(board[j][i] == '.') continue;
if (hs.contains(board[j][i]))
return false;
hs.add(board[j][i]);
}
hs.clear();
}
//检查每个小的3*3矩阵
for(int k = 0 ; k<9 ; k++){
for(int i = k/3*3 ; i < k/3*3+3 ; i++){
for(int j = (k%3)*3 ; j < (k%3)*3+3 ; j ++){
if(board[i][j] == '.') continue;
if(hs.contains(board[i][j])) return false;
hs.add(board[i][j]);
}
}
hs.clear();
}
return true;
}
public static void main(String[] args) {
char [][]arr =
{{'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'}
};
ValidSudo vs = new ValidSudo();
System.out.println(vs.FindValidSuso(arr));
}
}