https://leetcode-cn.com/problems/valid-sudoku
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 '.' 表示。
示例 1:
输入:
[
["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"]
]
输出: true
示例 2:
输入:
[
["8","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"]
]
输出: false
解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。
但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
说明:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
给定数独序列只包含数字 1-9 和字符 '.' 。
给定数独永远是 9x9 形式的。
思路:分别判断当前行是否有重复,每列是否重复,每个3*3小方格是否有重复
方法一:复杂度高
class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
char c=board[i][j];
if(c=='.'){
continue;
}
else{
for(int m=j+1;m<9;m++){
if(c==board[i][m]){
return false;
}
}
for(int m=i+1;m<9;m++){
if(c==board[m][j]){
return false;
}
}
if(!f(board,c,i,j))
return false;
}
}
}
return true;
}
//判断所属3*3小方格是否重复
public boolean f(char[][] board,char c,int i,int j){
int si=i/3;
int sj=j/3;
for(int m=si*3;m<(si+1)*3;m++){
for(int n=sj*3;n<(sj+1)*3;n++){
if(m==i&&n==j){
continue;
}
if(board[m][n]==c){
return false;
}
}
}
return true;
}
}
方法二:最优解
用三个二维数组存储当前数字在当前行、当前列、当前3*3小方格内是否已经出现过, 出现过为true否则为false
public class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[][] row=new boolean[9][10];
boolean[][] col=new boolean[9][10];
boolean[][] fangge=new boolean[9][10];
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
char c=board[i][j];
if(c!='.'){
int num=Integer.valueOf(String.valueOf(c));//字符转数字
if(row[i][num]||col[j][num]||fangge[i/3*3+j/3][num]){
return false;
}
row[i][num]=true;
col[j][num]=true;
fangge[i/3*3+j/3][num]=true;//当前是第几个小方格
}
}
}
return true;
}
}