标签:
Valid Sudoku
Determine whether a Sudoku is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character .
.
The following partially filed sudoku is valid.
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
What is Sudoku
?
////这题很直接
////验证每一行,每一列和每一个小九宫格的数字是否重复
///代码可以优化下,把验证过程单独写一个方法。
class Solution { /** * @param board: the board @return: wether the Sudoku is valid */ public boolean isValidSudoku(char[][] board) { int m=board.length; int n=board[0].length; if(board.length!=9 || board[0].length!=9) return false; boolean isRow=isValidRow(board); boolean isCol=isValidCol(board); boolean isNine=isValidNine(board); if(isRow && isCol && isNine) { return true; } else return false; } public boolean isValidRow(char[][] board) { for(int i=0;i<9;i++) { boolean[] isValid=new boolean[10]; int val=0; for(int j=0;j<9;j++) { if(board[i][j]==‘.‘) { continue; } else { val=board[i][j]-‘0‘; } if(isValid[val]) { return false; } else { isValid[val]=true; } } } return true; } public boolean isValidCol(char[][] board) { for(int i=0;i<9;i++) { boolean[] isValid=new boolean[10]; int val=0; for(int j=0;j<9;j++) { if(board[j][i]==‘.‘) { continue; } else { val=board[j][i]-‘0‘; } if(isValid[val]) { return false; } else { isValid[val]=true; } } } return true; } public boolean isValidNine(char[][] board) { for(int i=0;i<9;i+=3) { for(int j=0;j<9;j+=3) { boolean[] isValid=new boolean[10]; int val=0; for(int a=0;a<3;a++) { for(int b=0;b<3;b++) { if(board[i+a][j+b]==‘.‘) { continue; } else { val=board[i+a][j+b]-‘0‘; } if(isValid[val]) { return false; } else { isValid[val]=true; } } } } } return true; } };
标签:
原文地址:http://www.cnblogs.com/kittyamin/p/5018213.html