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.
思路:本题就是判断这个二维数组中,每一行是否有重复的数字,每一列是否有重复的数字和9方格中是否有重复的数字
代码如下(已通过leetcode)
public class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i=0;i<board.length;i++)
if(!isrerow(board, i)) return false;
for(int j=0;j<board[0].length;j++)
if(!isrecol(board, j)) return false;
for(int i=0;i<board.length-2;i=i+3){
for(int j=0;j<board[0].length-2;j=j+3) {
if(!isre9num(board, i, j)) return false;
}
}
return true;
}
public boolean isrerow(char[][] board,int row) {
int[] a= new int[10];
for(int j=0;j<board[row].length;j++){
if(board[row][j]!='.') a[board[row][j]-'0']++;
}
for(int j=0;j<a.length;j++) {
if(a[j]>1) return false;
}
return true;
}
public boolean isrecol(char[][] board,int col) {
int[] a= new int[10];
for(int i=0;i<board.length;i++){
if(board[i][col]!='.') a[board[i][col]-'0']++;
}
for(int i=0;i<a.length;i++) {
if(a[i]>1) return false;
}
return true;
}
public boolean isre9num(char[][] board,int row,int col) {
int[] a= new int[10];
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
if(board[row+i][col+j]!='.')
a[board[row+i][col+j]-'0']++;
}
}
for(int i=0;i<a.length;i++) {
if(a[i]>1) return false;
}
return true;
}
}