题目:Valid Sudoku
难度:easy
问题描述:
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.
解题思路:
问题的关键在于约束是什么,数独是否有效有三点需要判断:
1.每一横行没有重复数字。
2.每一纵行没有重复数字。
3.每一九宫格没有重复数字。
可以实现一个函数 isnotchongfu(char[] c)来判断输入的九个数是否重复。接下来就是找到所有需要判别的字符数组即可。
具体代码如下:
public class Solution {
int[]temp=new int[9];
char[]temp2=new char[9];
char c;
public boolean isValidSudoku(char[][] board) {
//横向不重复
System.out.println("你好");
int i,j,k=0;
for(i=0;i<9;i++){
if(!isnotchongfu(board[i])){
return false;
}
}
System.out.println("heng");
//3*3不重复
for(i=0;i<3;i++){
for(j=0;j<3;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=0;i<3;i++){
for(j=3;j<6;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=0;i<3;i++){
for(j=6;j<9;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=3;i<6;i++){
for(j=0;j<3;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=3;i<6;i++){
for(j=3;j<6;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=3;i<6;i++){
for(j=6;j<9;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=6;i<9;i++){
for(j=0;j<3;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=6;i<9;i++){
for(j=3;j<6;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
for(i=6;i<9;i++){
for(j=6;j<9;j++){
temp2[k++]=board[i][j];
}
}
if(!isnotchongfu(temp2)){
return false;
}
k=0;
//纵向不重复
for(i=0;i<9;i++){ //反置
for(j=i;j<9;j++){
c=board[i][j];
board[i][j]=board[j][i];
board[j][i]=c;
}
}
for(i=0;i<9;i++){
if(!isnotchongfu(board[i])){
return false;
}
}
System.out.println("zong");
return true;
}
public boolean isnotchongfu(char[] nums){
for(int j=0;j<9;j++){
temp[j]=0;
}
for(int i=0;i<9;i++){
c=nums[i];
if(c!='.'){
if(temp[(int)(c-'1')]==0){
temp[(int)(c-'1')]++;
}else{
return false;
}
}
}
return true;
}
}
对于3*3的9个数的取值,我还没有方便的方法,希望大家的指正!