两者存储方式,用数组 或者 数组与哈希表结合来存储。
一、数组
用三个9*9数组,存储81个状态,以num=board[i][j]-'1'为另一维索引,即以表中的数字为索引。
Java:
class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[][] row=new boolean[9][9];
boolean[][] column=new boolean[9][9];
boolean[][] box=new boolean[9][9];
int num,boxindex;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]!='.'){
num=board[i][j]-'1';
boxindex=(i/3)*3+j/3;
if(row[i][num]==true||column[num][j]==true||box[boxindex][num]==true){
return false;
}
row[i][num]=true;//一行
column[num][j]=true;//一列
box[boxindex][num]=true;//一个box,这里也是一行
}
}
}
return true;
}
}
C++:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool row[9][9]={0};
bool column[9][9]={0};
bool box[9][9]={0};
int num,boxindex;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]!='.'){
num=board[i][j]-'1';
boxindex=(i/3)*3+j/3;
if(row[i][num]==true||column[num][j]==true||box[boxindex][num]==true){
return false;
}
row[i][num]=true;
column[num][j]=true;
box[boxindex][num]=true;
}
}
}
return true;
}
};
二、哈希表存储
声明哈希表数组,一行(列)由一个哈希表存储,存储之前先判断对应的哈希表中是否存在该key。相比较于力扣给的答案,我觉得我这种更清晰明了一些,我也是在他基础上有一些改进。
Java:
class Solution {
public boolean isValidSudoku(char[][] board) {
HashSet<Integer>[] rows=new HashSet[9];//声明数组
HashSet<Integer>[] columns=new HashSet[9];
HashSet<Integer>[] boxes=new HashSet[9];
for(int i=0;i<9;i++){
rows[i]=new HashSet<Integer>();//为每一行分配空间
columns[i]=new HashSet<Integer>();
boxes[i]=new HashSet<Integer>();
}
int num,boxindex;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]!='.'){
num=board[i][j]-'1';
boxindex=(i/3)*3+j/3;
if(rows[i].contains(num)||columns[j].contains(num)||boxes[boxindex].contains(num)){
return false;
}
rows[i].add(num);
columns[j].add(num);
boxes[boxindex].add(num);
}
}
}
return true;
}
}
C++:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_set<int> rows[9];
unordered_set<int> columns[9];
unordered_set<int> boxes[9];
int num,boxindex;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]!='.'){
num=board[i][j]-'1';
boxindex=(i/3)*3+j/3;
if(rows[i].count(num)||columns[j].count(num)||boxes[boxindex].count(num)){
return false;
}
rows[i].insert(num);
columns[j].insert(num);
boxes[boxindex].insert(num);
}
}
}
return true;
}
};